简体   繁体   English

使用 chrome 扩展在 iframe 中注入 javascript

[英]Inject javascript in an iframe using chrome extension

There are lots of questions/answers on injecting javascript into the document page.有很多关于将 javascript 注入文档页面的问题/答案。 What I really want to do is inject javascript in an iframe within the document.我真正想做的是在文档的 iframe 中注入 javascript。

To be clear, that iframe doesn't belong to the same domain as the document.需要明确的是,该 iframe 与文档不属于同一域。 I've already tried it through console (not through extension) but was unable to do so.我已经通过控制台(而不是通过扩展)尝试过它,但无法这样做。

I'm very curious if this is something that can be done using a chrome-extension ?我很好奇这是否可以使用 chrome-extension 来完成?

Yes, you can use content_scripts property in manifest.json like this:是的,您可以像这样在 manifest.json 中使用content_scripts属性:

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

By setting all_frames to true you will inject/include content_frame.js javascript file into top document and all iframes.通过将all_frames设置为true您会将content_frame.js javascript 文件注入/包含到顶级文档和所有 iframe 中。 In case you just need javascript injected in iframe but not in top document you can check inside your content_frame.js file like this:如果您只需要在 iframe 中注入 javascript 而不是在顶级文档中,您可以像这样检查content_frame.js文件:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM