0

在我的代碼中,我目前有一個內容腳本,它將消息發送到後臺腳本,並作爲響應創建警報。這適用於example.jsbackground.js訪問https://www.google.com時。然而,試圖popup.js和我的內容腳本之間建立溝通的時候,我得到錯誤信息內容腳本可以連接到後臺腳本,但popup.js無法連接到內容腳本

Could not establish connection. Receiving end does not exist. 

我現在已經是我從popup.js發送消息一旦在彈出按鈕被點擊。然後,應該從內容腳本example.js中顯示一個控制檯消息,但它似乎甚至沒有到達內容腳本的偵聽器。下面的代碼,

popup.js:

window.onload=function(){ 
    document.getElementById('highlight').addEventListener('click', sendHighlightMessage, false); 
} 

function sendHighlightMessage() { 
    chrome.tabs.query({active: true, currentWindow: true}, function(tabs) { 
    console.log("going through tabs " + tabs[0].url); //this actually occurs 

     chrome.tabs.sendMessage(tabs[0].id, {highlight: true}, function(response) { 
     if (chrome.runtime.lastError) { 
      // An error occurred :(
      console.log("ERROR: ", chrome.runtime.lastError); 
     } 
     else{ 
      console.log(response.message); 
     } 
     }); 
    }); 
} 

example.js:

chrome.runtime.sendMessage('Hello World'); 
chrome.tabs.onMessage.addListener(function(response, sender, sendResponse){ 
    console.log("received " + response); //never gets to this point 
    sendResponse({message : "Response Received"}); 
}); 

background.js:

chrome.runtime.onMessage.addListener(function(response, sender, sendResponse){ 
    alert(response); 
}); 
chrome.tabs.onMessage.addListener(function(response, sender, sendResponse){ 
console.log("received " + response); 
sendResponse({message : "Response Received"}); 
}); 

我已經嘗試了很多答案,但目前爲止似乎沒有任何工作。

+0

「似乎還沒有達到」你看起來似乎是什麼意思?你在devtools中有一個調試器來確切地知道發生了什麼。在內容腳本偵聽器(devtools - Sources面板 - 內容腳本)中設置一個斷點,然後打開彈出窗口的devtools並單步執行代碼或設置斷點。這不應該超過一分鐘。 – wOxxOm

回答

-3

彈出式腳本被設計爲不能直接與內容腳本對話,您必須通過後臺腳本發送消息來完成此操作。

讓您的彈出窗口先將消息發送到後臺頁面,讓後臺頁面發送另一條消息到特定的內容腳本。讓您的內容腳本從後臺頁面監聽事件。

+0

謝謝你的回覆,我試着按照你所說的基本上將相同的偵聽器添加到'background.js'(檢查編輯的清晰度),但我似乎無法獲得後臺腳本和'popup「之間的連接。也是。 –

+1

'彈出式腳本被設計爲不能直接與內容腳本對話 - 這不是事實。當彈出窗口顯示時,彈出腳本可以直接與內容腳本進行通信**。 – wOxxOm