0

를 반환. 백그라운드 스크립트에서 콘텐츠 스크립트로 메시지를 보내려는 시도를하고 있지만 콘텐츠 스크립트에서 반환 된 개체는 항상 비어 있습니다.크롬 확장 메시징 : sendResponse이 나는 크롬 확장 프로그램을 짓고 있어요 나는 상황에 맞는 메뉴에서 사용자를 클릭 한 후 현재 선택된 텍스트를 얻으려면 빈 객체

background_script.js :

function onClickHandler(info, tab){ 
    chrome.tabs.query({active: true, currentWindow: true}, function(tabs) { 
     chrome.tabs.sendMessage(tabs[0].id, {method: "getSelection"}, undefined, function(response){ 
      console.log(response.data); // <--- this is undefined 
     }); 
    }); 
} 

chrome.contextMenus.onClicked.addListener(onClickHandler); 

content_script.js : 비슷한에

chrome.runtime.onMessage.addListener( 
    function(request, sender, sendResponse) { 
     if (request.method == "getSelection"){ 
      var selection = window.getSelection(); // <--- this is ok 
      sendResponse({data: selection}); 
      return true; 
     } 
    } 
) 

manifest.json을

{ 
    "manifest_version": 2, 

    "name": "Browser Extension", 
    "description": "Browser Extension", 
    "version": "0.1", 

    "background": { 
     "scripts": [ 
      "background_script.js" 
     ] 
    }, 

    "content_scripts": [ 
     { 
      "matches": ["<all_urls>"], 
      "js": ["content_script.js"] 
     } 
    ], 

    "permissions": [ 
     "activeTab", 
     "contextMenus", 
     "storage" 
    ] 
} 

주요 문제

다음은 관련 코드입니다 사례가 본다. ms가 누락되었습니다 return true; 성명을하지만 나는 그것을 추가했습니다. 또한 chrome.tabs.sendMessage 함수에는 새 매개 변수 options이 있지만 생략하거나 정의되지 않은 값이나 비어있는 값을 전달하는지 여부는 아무런 차이가 없습니다.

당신을 감사하지 :)

편집 : SendMessage 함수에서 chrome.runtime.lastError 때문에 정의되지 명백한 오류를!

+1

는 chrome.tabs.sendMessage''의 3 인자로 정의되지 않은 사용하지 마십시오. 단순히 인수를 제거, 즉 : [0] .ID'chrome.tabs.sendMessage (탭, {방법 : "대해 getSelection"}, 기능 (응답) {' –

+0

감사 @의 이반, 그건 내가 처음부터 그것을 어떻게하지만, 불행하게도 어쨌든 작동하지 않습니다 :( – squeck

+0

는'Selection' 복잡한 DOM 클래스 당신이()가' – wOxxOm

답변

0

으로는 @wOxxOm 지적, 여기에 문제는 복잡한 객체를 JSONify하려고했던 것이 었습니다. .toString을 추가하면 작동합니다. 내 잘못이야!

관련 문제