how to: dynamically load google ajax api into chrome extension content script
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 .ge开发者_如何学CtScript()
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!
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.
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
精彩评论