2012-07-27 53 views
0

当我尝试在我的扩展中包含jQuery库时,JS引擎给我一个错误。这是代码:Chrome扩展 - 为什么JS会抱怨,当我包含jQuery库?

chrome.tabs.executeScript(null,{code:" 
    if (typeof jQuery == 'undefined') { 
     var script = document.createElement('script'); 
     script.setAttribute('type') = 'text/javascript'; 
     script.setAttribute('src') = 'http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js'; 
     document.getElementsByTagName('head')[0].appendChild(script); 
    }; 
"}); 

和这个结果:

Uncaught ReferenceError: Invalid left-hand side in assignment (anonymous function)

这段代码被写入popup.js文件,包括在由popup.html。

甚至当我做这样的事情:

chrome.tabs.executeScript(null, {file: "browser.js", allFrames: true}, window.close());

,并在browser.js我指定以上(其中包括我的jQuery库)编写的代码,它发生同样的东西。最奇怪的是jQuery看起来并没有被定义,甚至当代码执行的选项卡已经删除它时(例如Flickr)。事实上,typeof jQuery总是被设置为'undefined'。我很困惑...

回答

0

因为它的语法无效JavaScript,正如错误消息告诉你的一样。函数调用返回的值不能是分配的左侧。

+0

是的,我在第一时间就这样做了。但是我有一些疯狂的错误,比如“jQuery没有定义”,所以我决定通过经典的JS sintax - 事实上这些错误再也没有出现过。事实上,我无法在我的扩展中包含jQuery! – Gianluca 2012-07-27 16:39:45

+0

http://stackoverflow.com/q/4947510/139010或http://stackoverflow.com/q/8745463/139010和[更多](http://stackoverflow.com/search?q=chrome+extension+ jQuery) – 2012-07-27 16:48:53

+0

我很抱歉为这样一个愚蠢的问题困扰你。我只是不知道“content_scripts”参数的存在。非常感谢你,你非常有帮助。 – Gianluca 2012-07-27 20:03:40

1
script.setAttribute('type') = 'text/javascript'; 

您正试图为方法指定一个字符串。你的语法无效。该错误与JQuery无关。

1

您错误地使用了setAttribute。您需要在传递值作为第二个参数,而不是用一个=

例如分配,

script.setAttribute('type', 'text/javascript'); 
+0

非常感谢!即使jQuery现在已经成功包含,(typeof jQuery =='undefined')仍然是真实的,我无法理解原因。 – Gianluca 2012-07-27 14:58:46

+0

@GianlucaSegato你根本不需要设置脚本类型(默认是JS)并且不使用'setAttribute()',直接设置属性:'script.src ='...'' – 2012-07-27 15:07:50

0
script.setAttribute('type') = 'text/javascript'; 

这是无效的。您想要:

script.setAttribute('type', 'text/javascript'); 

同样适用于src属性。

相关问题