如何将数据从远程窗口传回到Chrome扩展的后台页面? [英] How do I pass back data from a remote window to a chrome extension's background page?

查看:97
本文介绍了如何将数据从远程窗口传回到Chrome扩展的后台页面?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

  chrome.windows.create {
类型:'popup',
url:https://www.example.com/mypage.html
},函数(newWindow){

});

在我的远程页面( https://www.example.com/mypage.html )我正在等待用户执行操作。执行此操作时,我需要传回扩展名的一些数据。



我该怎么做?我找不到任何与文档相关的内容( http://developer.chrome.com/extensions/messaging .html

解决方案

基本上可以。你应该做的是使用内容脚本作为你新创建的窗口和后台脚本之间的桥梁。例如:

您的后台脚本:

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

});

您的内容脚本:

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



page.html code><脚本>
var go = function(){
var event = document.createEvent('Event');
event.initEvent('hello');
document.dispatchEvent(event);
}
< / script>
< a href =javascript:go();>点击我< / a>

所以,这个想法是使用文档对象从页面派发事件。内容脚本会监听该事件,一旦发生,就会将消息发送到最初代码所在的后台脚本。

I have a chrome extension, and from my background page I open a remote window:

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

    });

On my remote page (https://www.example.com/mypage.html) I am waiting for the user to perform an action. When this action is performed, I need to pass back to the extension some data.

How can I do this? I could not find anything relevant in the docs (http://developer.chrome.com/extensions/messaging.html)

解决方案

It is basically possible. What you should do is to use the content script as a bridge between your newly created window and your background script. For example:

Your background script:

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) {

});

Your content script:

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

page.html:

<script>
    var go = function() {
        var event = document.createEvent('Event');
        event.initEvent('hello');
        document.dispatchEvent(event);
    }
</script>
<a href="javascript:go();">Click me</a>

So, the idea is to dispatch an event from the page using document object. The content script listens for that event and once occur send a message to the background script where your code is originally.

这篇关于如何将数据从远程窗口传回到Chrome扩展的后台页面?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆