扩展页面间的通信

2018-05-31  本文已影响18人  SingleDiego

参考原文

知识点:




Chrome 提供了 4 个有关扩展页面间相互通信的接口,分别是:

做为一部入门级教程,此节将只讲解 runtime.sendMessageruntime.onMessage 接口,runtime.connectruntime.onConnect 做为更高级的接口请读者依据自己的兴趣自行学习,你可以在 http://developer.chrome.com/extensions/extension 得到有关这两个接口的完整官方文档。

请注意,Chrome 提供的大部分 API 是不支持在 content_scripts 中运行的,但 runtime.sendMessageruntime.onMessage 可以在 content_scripts 中运行,所以扩展的其他页面也可以同 content_scripts 相互通信。




runtime.sendMessage 完整的方法为:

chrome.runtime.sendMessage(extensionId, message, options, callback)

参数说明:




runtime.onMessage完整的方法为:

chrome.runtime.onMessage.addListener(callback)

此处的 callback 为必选参数,为回调函数。callback 接收到的参数有三个,分别是 messagesendersendResponse,即消息内容、消息发送者相关信息和相应函数。

其中 sender 对象包含4个属性,分别是 tabidurltlsChannelIdtab 是发起消息的标签。




下面我们写一个小例子来说明。

编写 manifest.json 文件:

{
    "manifest_version": 2,
    "name": "扩展内部通信Demo",
    "version": "1.0",
    "description": "扩展内部通信Demo",
    
    "browser_action": {
        "default_popup": "popup.html"
    },

    "background": {
        "scripts": [
            "js/background.js"
        ]
    }
}

我们的 popup.html 不需写入任何内容,只需引入一段 JS:

<script src="js/popup.js"></script>

编写 popup.js 文件:

// 发送消息,回调函数把接收到的回应写到网页中
chrome.runtime.sendMessage('Hello', function(response){
    document.write(response);
});

我们在 background 接收信息并处理,现在编写 background.js 文件:

// 接收消息,如果收到的消息是 'Hello',发送回应
chrome.runtime.onMessage.addListener(function(message, sender, sendResponse){
    if(message == 'Hello'){
        sendResponse('Hello from background.');
    }
});

最后插件的效果:


上一篇 下一篇

猜你喜欢

热点阅读