47

여러 가지 방법으로 반복적으로 질문을 받았지만 모든 답변을 통과하려고 시도했습니다 (아무도 놓치지 않았다). 나를 위해 일했다.Chrome 확장 프로그램 : 백그라운드에서 콘텐츠 스크립트로 sendMessage가 작동하지 않습니다.

매니페스트 : 여기

내 확장의 코드

{ 
"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 중 하나의 경고가 작동하지 않는 동안 작동합니다.

콘솔 로그 메시지 : 포트 오류 : 연결을 설정할 수 없습니다. 수신 종료가 없습니다.

내 잘못은 어디입니까? 당신의 배경 페이지에서

+0

'chrome.extension.sendMessage()'가 아닌 콘텐츠 스크립트에 메시지를 보내려면'chrome.tabs.sendMessage()'를 사용해야합니다. – apsillers

답변

89

대신 현재처럼 chrome.extension.sendMessage를 사용

chrome.tabs.query({active: true, currentWindow: true}, function(tabs){ 
    chrome.tabs.sendMessage(tabs[0].id, {action: "open_dialog_box"}, function(response) {}); 
}); 

를 호출해야합니다.

chrome.extension 함수는 메시지를 콘텐츠 스크립트로 보내지 만 다른 모든 확장 구성 요소는 메시지를 보냅니다.

+4

감사합니다. chrome.tabs.sendMessage' [전송할 탭을 지정해야합니다] (http://developer.chrome.com/extensions/messaging.html)를 제외하고는 정확합니다. 그래서 해결책은 다음과 같이 변경됩니다 :'chrome.tabs.query ({active : true}, function (tabs) { \t \t chrome.tabs.sendMessage (tab.id, {action : "open_dialog_box"}, function (response) { \t \t \t}); \t \t}), – Subway

+1

물론, 죄송합니다. 내 대답을 업데이트 할게. – apsillers

+0

좋아, 내가 질문에 추가 한 편집을 제거했습니다. – Subway