Andriuxa Andriuxa - 10 days ago 8
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

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.

Example:

content-script.js

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

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

frontend-script.js

window.postMessage({
    "foo": "data-from-frontend-script"
}, "*");
Comments