Chrome扩展消息传递-代码包括

Chrome Extension Message Passing - Code included

本文关键字:代码 包括 消息传递 扩展 Chrome      更新时间:2023-09-26

我有一个名为file.js的内容脚本,它创建变量"found"。我想发送的值变量"found"的文本框在弹出。html

在文件。js(我知道变量发现是工作的,使用警报测试)。

chrome.extension.sendRequest({foundlinks: found}, function(response) {
 console.log(response);
});
在Popup.html:

function pulllinks(){
chrome.extension.onRequest.addListener(function(request, sender, sendResponse) {
    document.getElementById("box").value = request.foundlinks;
  sendResponse({});
});

在弹出窗口。html:

<input type = "button" onclick="pulllinks();" name = "box" id="box" value = "Grab Links From Page"  /> 

但是,它什么也没做。什么好主意吗?

谢谢!

你需要在相反的方向发送请求-从弹出到内容脚本:

popup.html:

function pulllinks(){
    chrome.tabs.getSelected(null, function(tab) {
        chrome.tabs.sendRequest(tab.id, {cmd: "findLinks"}, function(response) {
            document.getElementById("box").value = response.foundlinks;
        });
    });
}

file.js:

chrome.extension.onRequest.addListener(function(request, sender, sendResponse) {
    if(request.cmd == "findLinks") {
        //calculate "found" value and send it back
        sendResponse({foundlinks: found});
    }
});

首先,您的onRequest侦听器应该从一开始就存在,因此将其移到pulllinks函数之外。其次,你如何确保你的sendRequest被解雇,而弹出是开放的?