如何:将 google ajax api 动态加载到 chrome 扩展内容脚本中
我正在尝试在 chorme 扩展的“内容脚本”中使用 google 的 ajax api。在常规的 html 页面上,我只会这样做:
<script src="http://www.google.com/jsapi"></script>
<script>
google.load("language", "1");
</script>
但是由于我试图从 js 代码动态加载翻译库,所以我尝试过:
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')
但最后一行抛出以下错误:
Uncaught TypeError: Object #<an Object> has no method 'load'
有趣的是,当我输入相同的内容时chrome 的 js 控制台中的“google.load('language','1')
”,它按预期工作...
我也尝试过使用 jquery 的 .getScript()
但同样的问题仍然存在...
有人知道可能是什么问题以及如何解决它吗?
非常感谢!
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!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我的工作是这样的:
它没有返回任何错误。
I have got this working like this:
It returned no errors.
内容脚本只能访问其自身或其他内容脚本的功能。由于您将 google api 加载器添加到文档的脚本中,因此您无法从内容脚本中调用它。 :)
如果您需要将 api 加载到文档的脚本中,您可以通过指定 autoload 参数来完成:
“
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
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