在我的代碼中,我目前有一個內容腳本,它將消息發送到後臺腳本,並作爲響應創建警報。這適用於example.js
和background.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"});
});
我已經嘗試了很多答案,但目前爲止似乎沒有任何工作。
「似乎還沒有達到」你看起來似乎是什麼意思?你在devtools中有一個調試器來確切地知道發生了什麼。在內容腳本偵聽器(devtools - Sources面板 - 內容腳本)中設置一個斷點,然後打開彈出窗口的devtools並單步執行代碼或設置斷點。這不應該超過一分鐘。 – wOxxOm