javascript - DOM Exception 12 for window.postMessage -


i'm learning build chrome extensions, , i'm trying follow 1 of instructions in official guide here.

what trying accomplish is:

  1. background.js shows page action targetted urls.
  2. page action executes script when clicked.
  3. executed script injects javascript on page.

so far, good! use following script inject page.

var injectjs = function(url, cb) {     var h = document.getelementsbytagname('head')[0],         s = document.createelement('script');     s.type = 'text/javascript';     s.src = url;     if (cb)         s.onload = cb;     h.appendchild(s); }; injectjs(chrome.extension.geturl('script/do_something.js')); 

now, want injected script able communicate extension.
seems looking what's described in documentation.

https://developer.chrome.com/extensions/content_scripts.html#host-page-communication

the problem is, when try window.postmessage console shows error "dom exception 12".


edit: first problem running sample code solved.
other error get, smae code port.postmessage:

uncaught error: attempting use disconnected port object

here's code:

var port = chrome.runtime.connect();  // respond messages injected script collect results window.addeventlistener('message', function(e) {     if (e.source != window)         return;     if (e.data.type && (e.data.type == 'from_page')) {         console.log('content script received: %s', e.data.text);         port.postmessage(e.data.text);     } }, false); 

basically i'm trying persist data temporarily while page reloads. content script/injected script collects data, , loads next page. background script should hold results until pages have been loaded.

don't confuse port.postmessage in contentscript.js example window.postmessage.

port.postmessage chrome extension-specific api, intended pass messages around within extension, while window.postmessage javascript method used communicating frames. second argument window.postmessage required, , used validate whether target allowed receive message or not.

in case, using wildcard sufficient, because you're sending message page itself:

window.postmessage({ type: "from_page", text: "hello webpage!" }, "*");                                                                            ^^^

Comments

Popular posts from this blog

Why does Ruby on Rails generate add a blank line to the end of a file? -

keyboard - Smiles and long press feature in Android -

node.js - Bad Request - node js ajax post -