2013-08-17 36 views
3

contentscript.jsChrome擴展標籤SendMessage函數contentscript錯誤

chrome.runtime.onMessage.addListener(
    function(request, sender, sendResponse) { 
    console.log(sender.tab ? 
       "from a content script:" + sender.tab.url : 
       "from the extension"); 
    if (request.greeting == "hello") 
     sendResponse({farewell: "goodbye"}); 
    }); 

background.js

chrome.browserAction.onClicked.addListener(function(tab) { 
    chrome.tabs.query({active: true, currentWindow: true}, function(tabs) { 
     chrome.tabs.sendMessage(tabs[0].id, {greeting: "hello"}, function(response) { 
      console.log(response.farewell); 
     }); 
    }); 
}); 

這有時工作,有時沒有。

案件不起作用:

1)當我重新加載擴展,單擊現有選項卡 2)擴展程序圖標,當我添加一個斷點內background.js

案件做工作:

1)當我重新加載擴展並且重新加載/加載新標籤和沒有斷點內background.js加入

引發的錯誤通常是:

Port: Could not establish connection. Receiving end does not exist. lastError:29 
Error in event handler for 'undefined': Cannot read property 'farewell' of undefined TypeError: Cannot read property 'farewell' of undefined 
at chrome-extension://glbcapgiojbbnjhngjdmoglaamjbjjak/background.js:16:28 
at <error: illegal access> 
at Event.dispatchToListener (event_bindings:356:21) 
at Event.dispatch_ (event_bindings:342:27) 
at Event.dispatch (event_bindings:362:17) 
at Object.chromeHidden.Port.dispatchOnDisconnect (miscellaneous_bindings:258:27) 

有沒有人可以對此有所瞭解?我覺得特別奇怪的是,斷點會導致它失敗(就像暫停background.js會導致事件監聽器死掉一樣)

回答

1

事實證明,當在background.js中設置斷點時,tabs對象變爲:

0: Object 
active: true 
favIconUrl: "" 
highlighted: true 
id: 20 
incognito: false 
index: 0 
pinned: false 
selected: true 
status: "complete" 
title: "Developer Tools - chrome-extension://glbcapgiojbbnjhngjdmoglaamjbjjak/_generated_background_page.html" 
url: "chrome-devtools://devtools/devtools.html dockSide=right&toolbarColor=rgba(223,223,223,1)&textColor=rgba(0,0,0,1)" 
windowId: 19 

的事件偵聽器是在不同的標籤,因此「接收端不存在」。話雖如此,我需要找出一種方法將消息發送到正確的選項卡(我也做了一些重定向oauth2,所以它也與選項卡混淆)。

1

我猜..由於斷點,焦點移動到後臺腳本。 您對{active:true,currentWindow:true}使用了chrome.tabs.query函數,但後臺腳本沒有tabid。 如果您想使用斷點進行調試,您應該在回調函數內部指出一點。