2012-05-19 55 views
4
// 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"; 

在userscript運行這個網址:http://www.free-tv-video-online.me/player/sockshare.php?id=24DA6EAA2561FD60鉻userscript錯誤:「不安全的JavaScript嘗試訪問框架」

爲什麼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"); 
} 

回答

13

這是真的,普通的JavaScript不能訪問iframe中的內容,這是在不同的領域,出於安全原因。 但是,這絕不會停止Chrome,Tampermonkey或Greasemonkey中的用戶腳本。

您可以處理用戶腳本中的iframed內容,因爲Chrome(和Firefox)處理iframe'd頁面就像它們是主頁面一樣。考慮到這一點,腳本編寫這樣的頁面很簡單。

例如,假設您在在此頁面domain_A.com:如果您設置@match指令這樣

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


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

那麼你的腳本將運行兩次 - 一次在主頁面上,一次在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"); 
} 

你會看到在淺綠色的主頁,並在粉紅色的iFrame網頁。


或者,您也可以測試這樣的:

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




當你發現(每評論另一個答案),你可以disable the same origin policy on Chrome不要這樣做!你會開放給壞人建立的各種惡棍。除了邪惡的網站,許多名義上的「好」網站 - 允許用戶發佈內容 - 可能會追蹤,剽竊或欺騙你。

+0

哦,哇,完美的工作。把我的最終代碼放在OP中,謝謝你! –

+0

不客氣,樂意效勞! –

1

爲了安全理由,您的瀏覽器將不會讓你從另一個域訪問JavaScript的iframe中。

見上面的答案在這裏:

jQuery cross domain iframe scripting

+0

哦,我明白了。我誤解了錯誤(以及其他解釋)。你不知何故使它更容易理解:) –

+0

http://stackoverflow.com/a/6083677/1053937 - 找到一種方法禁用該安全選項:) –

+0

不期望你的用戶這樣做,雖然你呢? –

相關問題