chrome
插件的编写,以及插件的后台应用和插件对当前页面的控制
接下来要讨论当前访问页面与插件页面之间的通信。
index.js
修改为
$(document).ready(function(){ chrome.runtime.onMessage.addListener( function(request, sender, sendResponse) { console.log(sender.tab ? "来自内容脚本:" + sender.tab.url : "来自扩展程序"); if (request.greeting == "您好") sendResponse({farewell: "再见"}); }); })
test.js
$(document).ready(function(){ console.log("内容脚本发送"); chrome.runtime.sendMessage({greeting: "您好"}, function(response) { console.log(response.farewell); }); })
当我们开启插件,并访问网页时,查看通信示例效果
test.js
首先发送数据“您好”,index.js
监听消息事件,收到后先判断是扩展程序还是标签页发送的消息并打印在控制台,然后回复内容 再见,test.js