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

通常、異なるオリジンのwindowオブジェクトに直接アクセスする方法はありません。異なるフレームのコンテンツスクリプト間で安全に通信する場合は、バックグラウンドページにメッセージを送信する必要があります。バックグラウンドページは、メッセージをタブに送り返します。

次に例を示します。

の一部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':

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

別の方法は、を使用chrome.tabs.executeScriptbg.jsてメインコンテンツスクリプトの関数をトリガーすることです。

関連ドキュメント

于 2012-07-04T10:09:59.033 に答える
16

これは古い質問だと理解していますが、最近、それを解決するために半日を費やしました。通常、iframeの作成は次のようになります。

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

このフレームはページとは異なる原点を持ち、そのDOMを取得することはできません。ただし、css分離のためだけにiframeを作成する場合は、別の方法でこれを行うことができます。

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 に答える