2012-07-27 79 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屬性。

相關問題