43

我正在做一个插件来对界面进行一些转换。我不断收到unsafe javascript attempt to access frame with url.... Domains, protocols and ports must match(典型的跨站点问题)

但作为一个扩展,它应该可以访问 iframe 的内容http://code.google.com/chrome/extensions/content_scripts.html ...

有谁知道如何访问它的内容以便可以捕获它们?

4

2 回答 2

46

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.

Here is an example:

Part of 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});
}

Background script 'bg.js':

chrome.runtime.onMessage.addListener(function(message, sender) {
    if (message.sendBack) {
        chrome.tabs.sendMessage(sender.tab.id, message.data);
    }
});

An alternative method is to use chrome.tabs.executeScript in bg.js to trigger a function in the main content script.

Relevant documentation

于 2012-07-04T10:09:59.033 回答
16

我知道这是一个老问题,但我最近花了半天时间来解决它。通常创建 iframe 看起来像这样:

var iframe = document.createElement('iframe');
iframe.src = chrome.extension.getURL('iframe-content-page.html');

此框架与页面的来源不同,您将无法获取其 DOM。但是,如果您创建 iframe 只是为了隔离 css,您可以通过另一种方式执行此操作:

var iframe = document.createElement('iframe');
document.getElementById("iframe-parent").appendChild(iframe);
iframe.contentDocument.write(getFrameHtml('html/iframe-content-page.html'));
.......
function getFrameHtml(htmlFileName) {
    var xmlhttp = new XMLHttpRequest();
    xmlhttp.open("GET", chrome.extension.getURL(html/htmlFileName), false);
    xmlhttp.send();

    return xmlhttp.responseText;
}
.......
"web_accessible_resources": [   
    "html/htmlFileName.html",
    "styles/*",
    "fonts/*"
]

之后,您可以使用 iframe.contentDocument 访问 iframe 的 DOM

于 2016-04-22T13:28:27.910 回答