使用 chrome 扩展在 iframe 中注入 javascript

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19288202/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 15:00:23  来源:igfitidea点击:

Inject javascript in an iframe using chrome extension

javascriptjquerygoogle-chromeiframegoogle-chrome-extension

提问by coding_idiot

There are lots of questions/answers on injecting javascript into the document page. What I really want to do is inject javascript in an iframe within the document.

有很多关于将 javascript 注入文档页面的问题/答案。我真正想做的是在文档的 iframe 中注入 javascript。

To be clear, that iframe doesn't belong to the same domain as the document. I've already tried it through console (not through extension) but was unable to do so.

需要明确的是,iframe 与文档不属于同一个域。我已经通过控制台(而不是通过扩展)尝试过它,但无法这样做。

I'm very curious if this is something that can be done using a chrome-extension ?

我很好奇这是否可以使用 chrome-extension 来完成?

回答by Igor Jerosimi?

Yes, you can use content_scriptsproperty in manifest.json like this:

是的,您可以在 manifest.json 中使用content_scripts属性,如下所示:

"content_scripts": [{
    "matches": ["http://*/*", "https://*/*"],
    "js": ["content_frame.js"],
    "all_frames": true
}],

By setting all_framesto trueyou will inject/include content_frame.jsjavascript file into top document and all iframes. In case you just need javascript injected in iframe but not in top document you can check inside your content_frame.jsfile like this:

通过设置all_framestrue您将注入/包含content_frame.jsjavascript 文件到顶级文档和所有 iframe。如果您只需要在 iframe 中注入 javascript 而不是在顶级文档中,您可以content_frame.js像这样检查文件内部:

if (parent === top) {
    // here you can put your code that will run only inside iframe
}