0

내 코드에는 현재 백그라운드 스크립트에 메시지를 보내는 컨텐트 스크립트가 있으며 이에 대한 응답으로 경고가 생성됩니다. https://www.google.com을 방문하면 example.jsbackground.js에서 작동합니다. popup.js 내 콘텐츠 스크립트 사이의 통신을 설정하려고 할 때 그러나, 나는 오류 메시지컨텐트 스크립트는 백그라운드 스크립트에 연결할 수 있지만 popup.js는 컨텐트 스크립트에 연결할 수 없습니다.

Could not establish connection. Receiving end does not exist. 

내가 현재 가지고하면 팝업의 버튼이 클릭되면 내가 popup.js에서 메시지를 보낼 수 있습니다를 얻을. 그런 다음 콘텐트 스크립트 인 example.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 다음은 코드,

popup.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 - 소스 패널 - 컨텐트 스크립트)에 중단 점을 설정 한 다음 팝업창에서 devtools를 열고 코드를 단계별로 실행하거나 중단 점을 설정합니다. 1 분 이상 걸리지 않아야합니다. – wOxxOm

답변

-3

팝업 스크립트는 콘텐츠 스크립트와 직접 대화 할 수 없도록 설계되었으므로이를 수행하기 위해 백그라운드 스크립트를 통해 메시지를 보내야합니다.

팝업을 사용하여 배경 페이지로 먼저 메시지를 보내고 배경 페이지에서 특정 콘텐츠 스크립트로 다른 메시지를 보냅니다. 콘텐츠 스크립트에서 배경 페이지의 이벤트를 수신 대기하도록합니다.

+0

답장을 보내 주셔서 감사합니다. 기본적으로'background.js' (청취를 위해 편집을 확인하십시오)에 동일한 수신기를 추가하여 시도했지만 백그라운드 스크립트와 팝업 사이에 연결이없는 것 같습니다. js '중 하나입니다. –

+1

'팝업 스크립트는 콘텐츠 스크립트와 직접 대화 할 수 없도록 설계되었습니다. '- 사실이 아닙니다. 팝업 스크립트가 ** 표시되면 팝업 스크립트는 콘텐츠 스크립트와 직접 통신 할 수 있습니다 **. – wOxxOm