나는 질문이 여러 가지 방법으로 반복적으로 요청되었다는 것을 알고 있지만 모든 답변을 검토하려고 노력했지만 (누구도 그리워하지 않았 으면 좋겠다) 아무도 나를 위해 일하지 않았습니다.
내 확장 코드는 다음과 같습니다.
명백한:
{
"name": "test",
"version": "1.1",
"background":
{
"scripts": ["contextMenus.js"]
},
"permissions": ["tabs", "<all_urls>", "contextMenus"],
"content_scripts" : [
{
"matches" : [ "http://*/*" ],
"js": ["jquery-1.8.3.js", "jquery-ui.js"],
"css": [ "jquery-ui.css" ],
"js": ["openDialog.js"]
}
],
"manifest_version": 2
}
contextMenus.js
function onClickHandler(info, tab) {
if (info.menuItemId == "line1"){
alert("You have selected: " + info.selectionText);
chrome.extension.sendMessage({action:'open_dialog_box'}, function(){});
alert("Req sent?");
}
}
chrome.contextMenus.onClicked.addListener(onClickHandler);
chrome.runtime.onInstalled.addListener(function() {
chrome.contextMenus.create({"id": "line1", "type": "normal", "title": "I'm line 1", "contexts":["selection"]});
});
openDialog.js
chrome.extension.onMessage.addListener(function(msg, sender, sendResponse) {
if (msg.action == 'open_dialog_box') {
alert("Message recieved!");
}
});
백그라운드 페이지의 두 가지 경고는 작동하지만 content_script 중 하나는 작동하지 않습니다.
콘솔 로그 메시지 : 포트 오류 : 연결을 설정할 수 없습니다. 수신단이 없습니다.
내 잘못은 어디에 있습니까?
답변
백그라운드 페이지에서
chrome.tabs.query({active: true, currentWindow: true}, function(tabs){
chrome.tabs.sendMessage(tabs[0].id, {action: "open_dialog_box"}, function(response) {});
});
chrome.extension.sendMessage
현재 사용 하는 대신 사용 합니다.
chrome.tabs
반면, 변형, 컨텐츠 스크립트에 메시지를 보내는 chrome.extension
기능은 다른 모든 확장 구성 요소에 메시지를 전송합니다.
답변
@apsillers가 정확합니다. 또한 콘텐츠 스크립트 리스너에서 true를 반환하는 것을 잊지 마십시오. 그렇지 않으면 너무 일찍 닫힐 수 있습니다.
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
console.log(message)
return true
});
답변
다음은 콘텐츠 스크립트 파일에 메시지를 보내는 백그라운드 스크립트의 예입니다.
background.js
chrome.tabs.sendMessage(tabs[0].id,"your message");
content-script / content.js
chrome.runtime.onMessage.addListener(function (response, sendResponse) {
console.log(response);
});
답변
내 유스 케이스는 웹 페이지에서 백그라운드 스크립트로 메시지를 보내야했습니다. 나는 chrome.runtime.onMessageExternal
이 메시지를 잡곤했다.
이 리스너 내부에서 기본적으로 내 콘텐츠 스크립트로 메시지를 전달하여 작업을 수행 할 수 있었지만 콘텐츠 스크립트 onMessage 리스너가 메시지를 포착하지 못하는 이유를 알 수 없었습니다.
웹 페이지에서 메시지를 보내기 전에 1 초 동안 기다린 것으로 나타났습니다 (기본적으로로드 할 때 수행했습니다). 내 콘텐츠 스크립트를 치는 메시지를 볼 수있었습니다.
답변
