Google chrome extension 如何将数据从远程窗口传回chrome扩展';谁的背景页?

Google chrome extension 如何将数据从远程窗口传回chrome扩展';谁的背景页?,google-chrome-extension,message-passing,Google Chrome Extension,Message Passing,我有一个chrome扩展,从我的背景页面打开一个远程窗口: chrome.windows.create({ type : 'popup', url : "https://www.example.com/mypage.html" }, function(newWindow) { }); 在我的远程页面()上,我正在等待用户执行操作。执行此操作时,我需要向扩展返回一些数据 我该怎么做?我在文档中找不到任何相关内容()这基本上是可能的。您应该做的是使

我有一个chrome扩展,从我的背景页面打开一个远程窗口:

chrome.windows.create({
        type : 'popup',
        url : "https://www.example.com/mypage.html"
    }, function(newWindow) {

    });
在我的远程页面()上,我正在等待用户执行操作。执行此操作时,我需要向扩展返回一些数据


我该怎么做?我在文档中找不到任何相关内容()

这基本上是可能的。您应该做的是使用内容脚本作为新创建的窗口和背景脚本之间的桥梁。例如:

您的背景脚本:

chrome.runtime.onMessage.addListener(function(message, sender, sendResponse) {
    alert("message received");
});
chrome.windows.create({
    type : 'popup',
    url : "http://yoursite.com/page.html",
    type: "popup"
}, function(newWindow) {

});
您的内容脚本:

document.addEventListener("hello", function(data) {
    chrome.runtime.sendMessage("test");
})
page.html:


var go=函数(){
var event=document.createEvent('event');
initEvent('hello');
文件、调度事件(事件);
}

因此,我们的想法是使用document对象从页面发送事件。内容脚本将侦听该事件,并在事件发生后向原始代码所在的后台脚本发送消息

我相信你所做的事情不需要传递信息。(除非我遗漏了什么。)我正在尝试创建一个扩展,需要创建一个弹出窗口来查询用户的一些信息。首先我使用了消息传递,然后我阅读了以下页面:

在html页面中包含一个js,该页面使用extension.getBackgroundPage或runtime.getBackgroundPage[如果使用非持久性背景页面,则使用后者]获取背景脚本。在您的后台页面上调用函数可能很容易,如下所示:


extension.getBackgroundPage().sendDataOrWhateverYouCallIt(数据)

使用和。@RobW谢谢。尝试了“从网页发送消息”部分,但我发现“'External_connectable'需要Google Chrome dev频道或更新版本,这是稳定的频道”。这在生产中如何工作?奇怪的是,我找不到这种通信的完整示例,如果您有,我将不胜感激。需要注意的是,yoursite.com必须包含在manifest.json文件的“content_scripts”下。。。“匹配项”:[此处]。你的回答让我省心了,谢谢。
<script>
    var go = function() {
        var event = document.createEvent('Event');
        event.initEvent('hello');
        document.dispatchEvent(event);
    }
</script>
<a href="javascript:go();">Click me</a>