6
// the iframe of the div I need to access
var iframe = document.getElementsByTagName("iframe")[2];
var innerDoc = iframe.contentDocument || iframe.contentWindow.document;

// resize 'player' in the iframe
innerDoc.getElementById('player').width = "1000px";
innerDoc.getElementById('player').height = "650px";

この URL のユーザースクリプトで実行: http://www.free-tv-video-online.me/player/sockshare.php?id=24DA6EAA2561FD60

Chrome でこのエラーが発生し、スクリプトが失敗するのはなぜですか?:

Unsafe JavaScript attempt to access frame with URL http://www.sockshare.com/embed/24DA6EAA2561FD60 
from frame with URL http://www.free-tv-video-online.me/player/sockshare.php?id=24DA6EAA2561FD60. 
Domains, protocols and ports must match.

(私は基本的な Javascript ユーザーです)


最終コード、回答者に感謝します:

// ==UserScript==
// @name       Resize
// @include    http://www.free-tv-video-online.me/player/sockshare.php*
// @include    http://www.sockshare.com/*
// ==/UserScript==

if (!(window.top === window.self)) {
    var player = document.getElementById('player');
    setSize(player);
}

function setSize(player) {
    player.style.setProperty("width", "1000px");
    player.style.setProperty("height", "650px");
}
4

2 に答える 2

15

セキュリティ上の理由から、通常のJavaScriptは別のドメインにあるiframeコンテンツにアクセスできないのは事実です。 ただし、これはChrome、Tampermonkey、Greasemonkeyのユーザースクリプトを停止するものではありません。

Chrome(およびFirefox)はiframe化されたページをメインページであるかのように処理するため、ユーザースクリプトでiframedコンテンツを処理できます。それを考慮すると、そのようなページのスクリプトは簡単です。

たとえば、domain_A.comに次のページがあるとします。

<html>
<body>
    <iframe src="http://domain_B.com/SomePage.htm"></iframe>
</body>
</html>


@matchディレクティブを次のよう に設定した場合:

// @match http://domain_A.com/*
// @match http://domain_B.com/*

次に、スクリプトが2回実行されます。1回はメインページで、もう1回はスタンドアロンページであるかのようにiframeで実行されます。

したがって、スクリプトが次のようになっている場合:

// ==UserScript==
// @name  _Test iFrame processing in Chrome and Tampermonkey
// @match http://domain_A.com/*
// @match http://domain_B.com/*
// ==/UserScript==

if (/domain_A\.com/i.test (document.location.href) ) {
    //Main page
    document.body.style.setProperty ("background", "lime", "important");
}
else {
    //iFrame
    document.body.style.setProperty ("background", "pink", "important");
}

メインページはライムグリーンで、iframedページはピンクで表示されます。


または、次のようにテストできます。

if (window.top === window.self) {
    //--- Code to run when page is the main site...
}
else {
    //--- Code to run when page is in an iframe...
}




発見したように(別の回答のコメントごとに)、Chromeで同一生成元ポリシーを無効にすることができます。これをしないでください! あなたは悪い人々によって設定されたあらゆる種類のシェナニガンに自分自身を開いたままにします。邪悪なサイトに加えて、多くの名目上「良い」サイト(ユーザーがコンテンツを投稿できるようにする)は、潜在的にあなたを追跡、ハッキング、またはなりすましする可能性があります。

于 2012-05-19T22:35:44.863 に答える
1

セキュリティ上の理由から、お使いのブラウザでは、別のドメインから iframe 内の JavaScript にアクセスすることはできません。

ここで一番の答えを見てください:

jQuery クロス ドメイン iframe スクリプト

于 2012-05-19T15:53:37.570 に答える