Andriuxa Andriuxa - 1 year ago 93
Javascript Question

Chrome extension - remote page injection

I'm working on a Google Chrome extension.

What I need to do is:

  • Read contents of specific div,

  • Download contents from remote website.

  • Replace current div contents with downloaded data.

I'm informed that chrome prevents some of this-like interactions, but is there any way I can make this happen?
Injected JavaScript can not access remote website,
Content script cannot modify body of webpage
What can I do?

Answer Source

It is possible. Basic idea is:

CS = Content Script, defined in manifest. FS = Injected Script - A separate script file.

  1. Inject a script into the webpage (FS). This injection should happen in the CS. The FS than have full access to DOM and can manipulate it.
  2. Use window.addEventListener("message", function(){}); in CS. Use window.postMessage({foo: "mydata"}, "*") in FS or vice-versa. So you can post any data from and to the CS <=> FS. Loading the external data in the CS and send it to FS.

I've built some extensions with this technique and it works great.



var el = document.createElement('script');
el.setAttribute('type', 'text/javascript');
el.setAttribute('src', "frontend-script.js");

window.addEventListener("message", function (event) {
}, false);


    "foo": "data-from-frontend-script"
}, "*");
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download