0

Chrome拡張機能を構築していて、ユーザーがコンテキストメニューをクリックした後に現在選択しているテキストを取得したいとします。私はバックグラウンドスクリプトからコンテンツスクリプトにメッセージを送ることによってそれをやろうとしていますが、コンテンツスクリプトから返されたオブジェクトは常に空です。Chrome拡張メッセージ:空のオブジェクトを返す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を持っていますが、それを省略しても、未定義または空の値を渡しても差はありません。

ありがとうございました:)

EDIT:sendMessage関数でchrome.runtime.lastErrorはとても明白なエラー未定義ではありませんが!

+1

'chrome.tabs.sendMessage'の3番目の引数としてundefinedを使用しないでください。 'chrome.tabs.sendMessage(tabs [0] .id、{method:" getSelection "}、function(response){' –

+0

ありがとう@iván、それは私が最初に行ったのですが、残念ながらそれはとにかく動作していません:( – squeck

+0

'Selection'は複雑なDOMクラスです.JSONに対応していないので、' .toString() 'を追加する必要があります。 – wOxxOm

答えて

0

@wOxxOmで指摘されているように、ここでの問題は複雑なオブジェクトをJSON化しようとしていることでした。 .toStringを追加すると動作します。私の悪い!