4

I'm trying to make use of google's ajax apis in a chorme extension's "content script". On a regular html page, I would just do this:

<script src="http://www.google.com/jsapi"></script>
<script>
  google.load("language", "1");
</script> 

But since I'm trying to load the tranlation library dynamically from js code, I've tried:

script = document.createElement("script");  
script.src = "http://www.google.com/jsapi";  
script.type = "text/javascript";  
document.getElementsByTagName("head")[0].appendChild(script); 
google.load('language','1')

but the last line throws the following error:

Uncaught TypeError: Object #<an Object> has no method 'load'

Funny enough, when i enter the same "google.load('language','1')" in chrome's js console, it works as intended...

I've also tried with jquery's .getScript() but the same problem persists...

Does anybody have any clue what might be the problem and how it could be solved?

Many thanks in advance!

2 Answers 2

1

I have got this working like this:

<script type="text/javascript">
    var headID = document.getElementsByTagName("head")[0];
    var newScript = document.createElement('script');
    newScript.type = 'text/javascript';
    newScript.src = 'http://www.google.com/jsapi';
    headID.appendChild(newScript);
</script>
<script type="text/javascript">
    google.load("language", "1");
</script>

It returned no errors.

Sign up to request clarification or add additional context in comments.

1 Comment

how do you append this block from content-script.js? I am tried the same code from js file. it replaces all the content in the html with <head><script src="https://www.google.com/uds/?file=elements&amp;v=1&amp;packages=transliteration" type="text/javascript"></script><link href="https://www.google.com/uds/api/elements/1.0/3eced193c1ab3ba305519598439ccaef/transliteration.css" type="text/css" rel="stylesheet"><script src="https://www.google.com/uds/api/elements/1.0/3eced193c1ab3ba305519598439ccaef/transliteration.I.js" type="text/javascript"></script></head>
1

Content scripts may access only the functions of itself or other content scripts. Since you add google api loader to the document's scripts, you can't call it from your content script. :)

If you need to load apis into the document's scripts, you can do it by specifying autoload parameter : "https://www.google.com/jsapi?autoload=%7B%22modules%22%3A%5B%7B%22name%22%3A%22language%22%2C%22version%22%3A%221%22%7D%5D%7D"

http://code.google.com/apis/loader/autoloader-wizard.html

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.