问题描述
我正在做一个插件来对界面进行一些转换.我不断收到 unsafe javascript 尝试访问带有 url 的框架....域、协议和端口必须匹配
(典型的跨站点问题)
I'm doing a plugin to do some transformations to the interface. I keep getting unsafe javascript attempt to access frame with url.... Domains, protocols and ports must match
(typical cross site issue)
但作为扩展程序,它应该可以访问 iframe 的内容 http://code.google.com/chrome/extensions/content_scripts.html ...
But being an extension it should have access to the iframe's content http://code.google.com/chrome/extensions/content_scripts.html ...
有人知道如何访问它的内容以便可以捕获它们吗?
Doesn anyone know how to access it's contents so they can be capturable?
推荐答案
通常没有直接的方法来访问不同来源的 window
对象.如果您想在不同框架中的内容脚本之间安全通信,您必须向后台页面发送一条消息,后台页面又将消息发送回选项卡.
There's generally no direct way of accessing a different-origin window
object. If you want to securely communicate between content scripts in different frames, you have to send a message to the background page which in turn sends the message back to the tab.
这是一个例子:
manifest.json
的一部分:
"background": {"scripts":["bg.js"]},
"content_scripts": [
{"js": ["main.js"], "matches": ["<all_urls>"]},
{"js": ["sub.js"], "matches": ["<all_urls>"], "all_frames":true}
]
main.js
:
var isTop = true;
chrome.runtime.onMessage.addListener(function(details) {
alert('Message from frame: ' + details.data);
});
sub.js
:
if (!window.isTop) { // true or undefined
// do something...
var data = 'test';
// Send message to top frame, for example:
chrome.runtime.sendMessage({sendBack:true, data:data});
}
后台脚本'bg.js':
Background script 'bg.js':
chrome.runtime.onMessage.addListener(function(message, sender) {
if (message.sendBack) {
chrome.tabs.sendMessage(sender.tab.id, message.data);
}
});
另一种方法是使用 bg.js
中的 chrome.tabs.executeScript
来触发主内容脚本中的函数.
An alternative method is to use chrome.tabs.executeScript
in bg.js
to trigger a function in the main content script.
这篇关于从 chrome 的扩展内容脚本访问 iframe 内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!