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,但是忽略它還是傳遞未定義值或空值都沒有區別。

謝謝:)

編輯:chrome.runtime.lastError在SendMessage函數是不確定的所以沒有明顯的錯誤!

+1

不要使用undefined作爲'chrome.tabs.sendMessage'的第三個參數。簡單地消除該參數即:'chrome.tabs.sendMessage(tabs [0] .id,{method:「getSelection」},function(response){' –

+0

謝謝@iván,這就是我在第一時間做到的,不幸的是它無法正常工作:( – squeck

+0

'Selection'是一個複雜的DOM類,它不是JSON'ifiable,所以你需要添加'.toString()' – wOxxOm

回答

0

正如@wOxxOm指出的那樣,這裏的問題是我試圖對一個複雜的對象進行JSON化。添加.toString的作品。我的錯!

相關問題