谷歌浏览器插件开发教程7
从pane发送信息到 inject.js inject.js发送到pane
inject.js
window.addEventListener("message", function(e) { var info = e.data; var cmd = info.cmd; if (cmd == "sendinject") { var data = info.data; var action = data.action; if (action == "begin") { window.postMessage({ cmd: 'sendcontentscript', data: { action: "begin", list: "开始begin了", } }, '*'); } console.log(data); } }, false);
contentscript
function injectCustomJs(jsPath) { jsPath = jsPath || 'inject.js'; var temp = document.createElement('script'); temp.setAttribute('type', 'text/javascript'); // 获得的地址类似:chrome-extension://ihcokhadfjfchaeagdoclpnjdiokfakg/js/inject.js temp.src = chrome.extension.getURL(jsPath); temp.onload = function() { // 放在页面不好看,执行完后移除掉 this.parentNode.removeChild(this); }; document.head.appendChild(temp); } injectCustomJs(); // contentscript.js 发送到inject.js // chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) { window.postMessage({ cmd: 'sendinject', data: request }, '*'); }); window.addEventListener("message", function(e) { var info = e.data; var cmd = info.cmd; if (cmd == "sendcontentscript") { var data = info.data; var action = data.action; var list = data.list; if (action == "begin") { chrome.runtime.sendMessage({ greeting: '你好,我是content-script呀,我主动发消息给后台!' }, function(response) {}); } console.log(data); } }, false);
mypane.js
setTimeout(function(){ chrome.tabs.query({active:true, currentWindow:true}, function (tab) {//获取当前tab //向tab发送请求 chrome.tabs.sendMessage(tab[0].id, { action: "begin", list: "", }, function (response) { //test.js的数据 console.log(response); }); }) ; },200) chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) { $('body').html(JSON.stringify(request)); });
其实我发现 谷歌浏览器的通信机制并不好用 上面代码是短连接的写法 我打算用websocket代替谷歌浏览器插件通信
如果遇到什么不懂的地方直接关注公众号留言(本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须在文章页面给出原文连接,否则保留追究法律责任的权利。)
作者:newmiracle
出处:https://www.cnblogs.com/newmiracle/