One things I find myself having to reference a lot is communication between different scripts. And through enough testing and stuff I've figured out how to communicate between everything. So here is a list of code snippets of how to do so. In all of these examples, I will be setting the message variable in the receiver to "hello". Each sample will have two parts -> and <-, for most of these, the two must be used together!
Script -> Created window:
Script <- Created window:Code:var mywindow = window.open("url","_blank"); function sayHello(){ mywindow.message = "hello"; }
Content script -> Toolstrip/Background Page:Code:function sayHello(){ window.opener.message = "hello"; }
Content script <- Toolstrip/Background Page:Code:myport = chrome.extension.connect(); myport.onMessage.addListener(recv); myport.postMessage("hello"); function recv(msg){ message = msg; }
Toolstrip -> Background Page:Code:var myport; chrome.self.onConnect.addListener(listen); function listen(port){ myport = port; myport.onMessage.addListener(recv); myport.postMessage("hello"); } function recv(msg){ message = msg; }
Toolstrip <- Background Page:Code:var is_toolstrip = true; var v = chrome.self.getViews(); for(var i in v){ if(v[i].is_background_page){ v[i].message = "hello"; } }
Content script -> Matched page:Code:var is_background_page = true; var v = chrome.self.getViews(); for(var i in v){ if(v[i].is_toolstrip){ v[i].message = "hello"; } }
Content script <- Matched page:Code:contentWindow.message = "hello"; function sayHello(){ message = "hello"; } contentWindow.sayHello = sayHello;
Extension's content script <-> Different extension's content script:Code:sayHello(); //This function was injected by the content script, //and by the method of injection, is run in the content //script's scope rather than the page's.
I think that's everything! You can of course link these together to communicate between further away things (like a different extensions toolstrip from your background page, or a background page's opened window from your content script).Code:var myinterval,myid=chrome.extension.id_; var comm = contentWindow.document.getElementById("INTEREXTENSIONCOMMUNICATOR"); if(typeof(comm) == "undefined"){ comm = document.createElement("span"); comm.setAttribute("display","none"); comm.setAttribute("id","INTEREXTENSIONCOMMUNICATOR"); contentWindow.document.body.appendChild(comm); }e myinterval = setInterval(function(){ if(comm.value.substr(0,myid.length+1) != myid+":"){ var pos = comm.value.indexOf(":"); var extid = comm.value.substr(0,pos); console.log("Recieved message from extension "+extid); message = comm.value.substr(pos+1); comm.value = ""; } },100); function send(msg){ comm.value = myid+":"+msg; } send("hello");
If there's anything I forgot please mention it and I'll post the examples, but I don't think there is.
It'll be helpful for me even to not have to sift through my old code to remember how to do all this.. ^^;


LinkBack URL
About LinkBacks



Reply With Quote

