简体   繁体   English

将数据从Chrome扩展程序传递到网页

[英]Pass data from chrome extension to webpage

I am able to pass data from my webpage to chrome extension. 我可以将数据从我的网页传递到Chrome扩展程序。 My code goes as follows. 我的代码如下。

var id = "myExtensionId";
    chrome.runtime.sendMessage(id, { messageFromWeb: "Sample message" }, function (response) {
});

I am able to get the tab Id at the extension side. 我可以在扩展端获得选项卡ID。 But how can I send back data from the extension to the tab? 但是,如何将数据从扩展名发送回标签? Is the following code correct? 以下代码是否正确?

chrome.runtime.onMessageExternal.addListener(
    function(request, sender, sendResponse) {
        if (request.messageFromWeb) {
            console.log(request.messageFromWeb);
        }

        chrome.tabs.sendMessage(sender.tab.id,{ greeting: "hello" });
    }
);

The code, chrome.tabs.sendMessage(sender.tab.id,{ greeting: "hello" }); 代码, chrome.tabs.sendMessage(sender.tab.id,{ greeting: "hello" }); does not throw error. 不会抛出错误。 How should be listening at the web page to get events from extension? 如何在网页上收听从扩展中获取事件?

From content script to website script 从内容脚本到网站脚本

Because the content script and the scripts in the website can see the same DOM, you can use it to communicate between them. 由于内容脚本和网站中的脚本可以看到相同的DOM,因此您可以使用它在它们之间进行通信。 Is as easy as: 就像这样简单:

Content script: 内容脚本:

// data you want to sent
var data = {
    random: 'Some data',
    more: 'More data'
};

// send data through a DOM event
document.dispatchEvent(new CustomEvent('csEvent', {detail: data}));

Website script: 网站脚本:

// Listen you CRX event
document.addEventListener('csEvent', function (event) {
    var data = event.detail;

    // Do something with you data from CRX
});

From content script to background script 从内容脚本到后台脚本

How to do it depends on which type of connection you need: one-time or long-lived . 如何做到这取决于您需要哪种类型的连接: 一次性长期使用 From Chrome Developer page Messaging : 来自Chrome开发者页面消息

There is a simple API for one-time requests and a more complex API that allows you to have long-lived connections for exchanging multiple messages with a shared context. 有一个用于一次性请求的简单API和一个更复杂的API,它允许您使用长期连接来与共享上下文交换多个消息。

If you only want to send a response back, here is an example: 如果您只想发回一个回复,这里有一个例子:

chrome.runtime.onMessage.addListener(
    function(request, sender, sendResponse) {
        console.log(sender.tab ?
                "from a content script:" + sender.tab.url :
                "from the extension");

        sendResponse({farewell: "Message back!"});
    });

Edited to add content script to website script way 编辑将内容脚本添加到网站脚本方式

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM