1

现在我正在创建Chrome扩展程序。为此,我需要使用Google的Calendar Data API。这里是我的manifest.json文件:Chrome扩展程序和加载外部Google API Uncaught ReferenceError

{ 
"name": "Test", 
"version": "1.0", 
"background_page": "background.html", 
"content_scripts": [ 
    { 
    "matches": ["<all_urls>"], 
    "js": ["jquery.js", "content_script.js"] 
    } 
], 
"permissions": [ 
    "tabs", "http://*/*" 
] 

}

我试着加入以下清单文件的JS部分但加载扩展时抛出一个错误。

http://www.google.com/jsapi?key=keyhere 

我也尝试添加

document.write('<script type="text/javascript" src="http://www.google.com/jsapi?key=keyhere"></script>'); 

我background.html文件。然而,每当我打电话

google.load("gdata", "1"); 

我得到一个错误,说未捕获的ReferenceError:谷歌没有定义。为什么我的扩展不加载这个API时,加载其他的罚款?

回答

1

您不能在content_scripts中包含外部脚本。

如果要注入使用document.write,那么你需要屏蔽斜线在关闭标签<script>标签:

document.write('...<\/script>'); 

您可以包括您的外部API的js为背景页面,就像平常不过:

<script type="text/javascript" src="http://www.google.com/jsapi?key=keyhere"></script> 

如果你在内容脚本中需要这个api,那么你可以发送一个请求到你的后台页面,并要求它在那里做依赖于API的东西,然后把结果发送回你的内容脚本。

+0

我试着在普通的背景页面中添加它,但那也行不通。我在content_scripts中需要它,但我认为在background.html中加载它会自动允许我在content_scripts中使用它。 – joshholat 2010-10-16 16:06:11

+0

@joshholat背景页面几乎就是普通页面,没有任何限制。如果它不起作用,那么问题出在代码中。把你的背景页面放到web服务器的根目录下,然后在浏览器中打开它 - 我敢打赌它不会在那里工作。 – serg 2010-10-16 16:10:18

+0

将api js放入后台页面并不会自动将其加载到内容脚本中,它们是完全隔离的。为了在它们之间进行通信,您需要来回发送请求。 – serg 2010-10-16 16:13:15

0

感谢您的链接,它帮助了很多。但是,现在我遇到了另一个有趣的问题。

for (var i = rangeArray.length - 1; i >= 0; i--) { 
    var myLink = document.createElement('a'); 
    myLink.setAttribute('onclick','helloThere();'); 
    myLink.innerText ="GO"; 
    rangeArray[i].insertNode(myLink); 
} 

现在我得到的错误,“helloThere没有定义”,即使我把已经在相同的文件上面的循环当前函数大约十线上面的功能。为什么会发生这种情况?如果我这样做:

for (var i = rangeArray.length - 1; i >= 0; i--) { 
    var myLink = document.createElement('a'); 
    myLink.setAttribute('onclick','chrome.extension.sendRequest({greeting: "hello"}, function(response) { });'); 
    myLink.innerText ="GO"; 
    rangeArray[i].insertNode(myLink); 
} 

我得到遗漏的类型错误:无法调用“sendRequest将”未定义

+0

它可能会更好地把它作为另一个问题,因为它是不相关的。内容脚本和实际页面不共享可变空间,它们只共享DOM。 – serg 2010-10-16 19:58:55

+0

请勿使用字符串,请使用函数引用。而不是'myLink.setAttribute('onclick','helloThere();');'说'myLink.onclick = helloThere' – 2010-10-17 06:16:30

0

这是因为在你的代码中的一些语法错误。我有同样的问题。我启用了fire-bug插件,在fire狐狸中打开了我的background.html页面。火虫控制台应该是我的错误,我解决了它现在正在工作。

相关问题