2013-05-01 48 views
3

我正在寫我的第一個Google擴展程序代碼,並且出現了一個我從未見過的奇怪錯誤。chrome.webNavigation undefined

Uncaught TypeError: Cannot read property 'onCompleted' of undefined background.js:4 
(anonymous function) 

我很喜歡Javascript btw(儘管在Java方面有豐富的知識)。

我的代碼如下所示:

chrome.webNavigation.onCompleted.addListener(function(){//error right here 
if(hasHostSuffix(document.URL,'mysite.com')) 
{ 
    console.log("Web navigation commited!"); 
    var links = document.getElementsByName("a"); 
    for(var i = 0; i < links.length; i++) 
    { 
     console.log(links[i].getAttribute("href")); 
     if(links[i].style.backgroundColor='#272727') 
     { 
      links[i].className="gone"; 
     } 
    } 
} 
}); 

我一直沒能找到我的我收到此錯誤的任何可靠的信息。

任何幫助,將不勝感激:)

編輯:

被帶到了我的注意,我忘了一些重要的信息由xD我manfiest:

{ 
"manifest_version": 2, 
..., 
"permissions": [ 
    "webNavigation" 
], 
..., 
"content_scripts":[ 
    { 
     "matches":["http://www.mysite.com/*"], 
     "css":["ur_customstyle.css"], 
     "js":["background.js"] 
    } 
] 
} 
+2

webNavigation必須是未定義的。您是否在清單中添加了權限? - http://developer.chrome.com/extensions/webNavigation.html – 2013-05-01 00:20:30

+0

'chrome.webNavigation'的計算結果爲'undefined',所以你不能訪問'onCompleted'屬性。這是否被設置? (編輯:見上) – 2013-05-01 00:20:37

+0

@Rick這就是我的想法,但我有權限(只是忘了將我的清單添加到我的帖子o.O)。 – Brandon 2013-05-01 00:33:41

回答

9

chrome.webNavigation,因爲大多數鉻。 * API只能從擴展的後臺腳本訪問,而不能從內容腳本訪問。雖然您的文件名爲background.js,但您的清單顯示您正在將其用作內容腳本。

在這種情況下使用內容腳本是正確的,因爲您需要與DOM交互。從您發佈的代碼片段看來,您似乎不需要使用webNavigation API。您可以簡單地將清單中的內容腳本設置爲run_at: document_end,並在DOM完成後立即運行。檢查http://developer.chrome.com/extensions/content_scripts.html

+0

非常感謝。非常簡單的問題和TIL更多關於鉻的API。 – Brandon 2013-05-01 17:48:02

+2

有沒有在內容腳本中使用webNavigation的方法? – 2013-08-25 04:11:50

+0

@KevenWang,不,沒有。 – wOxxOm 2017-06-16 11:49:23