code_prettify

2013年8月8日 星期四

跨 frame資料存取,不考慮 cross-domain

pseudo code
<html>
......
<iframe id="frame1">
<iframe id="frame2">
</html>

iframe1:
<html>
<html>

iframe2
<html>
<input type="text" name="isOk" value="0"
<html>
需求是在 iframe1裡面需要 iframe2的 isOk的值作判斷
直覺的 javascript(in iframe1):
var isOk = parent.document.getElementById('iframe2').document.getElementById('isOk');
.....
但是測了半天才發現 parent.document.getElementById('iframe2')根本沒拿到 iframe2而是拿到 parent.
印出 parent.document.getElementById('iframe2').document.body.innerHTML才發現根本是 parent的內容.

解決方法:
改用 parent.frames['iframe2']

觀念錯誤處:尚未找出.還是不知道為什麼 parent.document.getElementById('iframe2')拿不到 iframe2

收穫:搜尋過程中找到幾個
Web technology for developers
window.frames解說
each item in the window.frames pseudo-array represents the window object corresponding to the given <frame>'s or <iframe>'s content, not the (i)frame DOM element (i.e. window.frames[ 0 ] is the same thing as document.getElementsByTagName( "iframe" )[ 0 ].contentWindow)
iframe scripting
From the DOM iframe element, scripts can get access to the window object of the included HTML page via the contentWindow property. ThecontentDocument property refers to the document element inside the iframe (this is equivalent to contentWindow.document), but is not supported by Internet Explorer versions before IE8.

4 則留言:

Unknown 提到...

嗨~ 如果iframe是根本網頁不同的domain 會發生錯誤 不知道怎麼解決 想請教一下 錯誤訊息如下"Uncaught SecurityError: Failed to read the 'contentDocument' property from 'HTMLIFrameElement': Blocked a frame with origin "null" from accessing a frame with origin "https://www.shef.ac.uk". The frame requesting access has a protocol of "file", the frame being accessed has a protocol of "https". Protocols must match." 謝謝~

Unknown 提到...

嗨~ 如果iframe是根本網頁不同的domain 會發生錯誤 不知道怎麼解決 想請教一下 錯誤訊息如下"Uncaught SecurityError: Failed to read the 'contentDocument' property from 'HTMLIFrameElement': Blocked a frame with origin "null" from accessing a frame with origin "https://www.shef.ac.uk". The frame requesting access has a protocol of "file", the frame being accessed has a protocol of "https". Protocols must match." 謝謝~

ELie 提到...

跨網域抱歉我也不知怎解。如果只是網頁遊戲我是用過 local架一個網域尾巴一樣的apache(用host把 localhost map到這個假網域)然後把js佈署到這個 apache上執行來繞過,但這不適用在正常的工業環境

ELie 提到...

跨網域抱歉我也不知怎解。如果只是網頁遊戲我是用過 local架一個網域尾巴一樣的apache(用host把 localhost map到這個假網域)然後把js佈署到這個 apache上執行來繞過,但這不適用在正常的工作環境