从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代替谷歌浏览器插件通信