从chrome.runtime.sendMessage获取未定义的响应?

时间:2018-02-01 16:32:30

标签: javascript google-chrome google-chrome-extension

我正在构建一个chrome扩展程序,它会获取用户在网页中选择的一些文本,然后在单击按钮时将其显示在弹出窗口中。我正在使用chrome.runtime API执行此操作。

但是当chrome.runtime.sendMessage执行时,我得到一个未定义的响应,导致以下错误:TypeError: Cannot read property 'data' of undefined

代码:

function pasteSelection() {
    chrome.runtime.sendMessage( {"method": "getSelection"}, function(response) {
        var text = document.getElementById('text');
        text.innerHTML = response.data;
    });
}

window.onload = function() {
    document.getElementById("myButton").addEventListener("click", pasteSelection);
}

chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
    if (request.method == "getSelection")
        sendResponse({"data": window.getSelection().toString()});
    else
        sendResponse({});
});

我试图按照说明of this answer。作者使用的一些方法已被弃用。

更新

我已将代码分成两个文件并做了一些小改动,我也在显示我的manifest.json文件。

popup.js

function pasteSelection() {
    chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
        var currTab = tabs[0];
        var tab_id = currTab.id;
        chrome.tabs.sendMessage(tab_id, {method: "getSelection"}, function(response) {
            var text = document.getElementById('text');
            text.innerHTML = response.data;
        });
    });
}

document.addEventListener('DOMContentLoaded', () => {
    document.getElementById("myButton").addEventListener("click", pasteSelection);
});

selection.js

chrome.runtime.onMessage.addListener(function(message, sender, sendResponse) {
    if (message.method == "getSelection")
        sendResponse({data: window.getSelection().toString()});
    else
        sendResponse( {} );
    return true;
});

的manifest.json

   {
    "manifest_version": 2,
    "name": "Code snippets",
    "description": "Extension that enables users to save and tag code snippets and easily navigate through them",
    "version": "1.0",
    "browser_action": {
        "default_title": "Code Snippets",
        "default_popup": "interface.html"
    },
    "content_scripts": [
        {
            "matches": ["http://*/*", "https://*/*"],
            "js": ["selection.js"]
        }
    ],
    "permissions": [
        "tabs"
    ]
}

0 个答案:

没有答案