Chrome extension to remove DOM elements inside ifr

2019-04-15 02:47发布

I would like to know all the components and steps needed to create a Google Chrome extension that will be able to remove some DOM elements from inside an iframe within a certain page.

My research indicates that this is not possible through common javascript due to the same origin policy.

Manually removing the DOM elements from code inspection in Chrome is as far as I got, but I want to automate this.

From other similar questions (mainly this one), it appears that a Chrome extension should be able to do this. I believe this is the most similar question but has not been answered as of yet, and also isn't as clear.

In all honesty, I could take it from here, but I think other people might benefit from this question and the answer, even if I end up answering myself.

Example HTML:

<!DOCTYPE html>
<html>
<body>
    <iframe src="iframe.htm"></iframe>
</body>
</html>

And iframe.htm:

<!DOCTYPE html>
<html>
<body>
    <div id="targetDiv"></div>
</body>
</html>

The end result should be the same as running (with jQuery):

$('#targetDiv').remove();

which of course does not work.

1条回答
Deceive 欺骗
2楼-- · 2019-04-15 03:24

I accomplished what I wanted so here's the answer.

The first thing you need for Chrome extensions is the manifest file, manifest.json. Here is a working example:

{
  "manifest_version": 2,

  "name": "iframe manipulation extension example",
  "description": "This extension allows to run scripts that manipulate cross domain IFRAME contents.",
  "version": "1.0",

  "permissions": [
    "*://target-site.com/*"
  ],
  "content_scripts": [
    {
      "matches": [
        "*://target-site.com/*"
      ],
      "js": ["script.js"],
      "all_frames": true
    }
  ]
}

It has some self-explanatory values and then permissions and content_scripts. It basically says that this extension will only work when accessing target-site.com. We specify the file we want to run and also set "all_frames": true, which will run said file for each frame in the page.

You can of course run whatever javascript you need in the file/s you reference in your manifest.

Navigate to chrome://extensions/ to load your unpacked extension or pack it.

Please note there are other ways to get an extension to run scripts. This is just what I ended up with as the easiest way.

查看更多
登录 后发表回答