Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
156 views
in Technique[技术] by (71.8m points)

javascript - How to access inside frame

How to access into iframe:

var iframe = document.getElementById('sitefield1');
var innerDoc = iframe.contentDocument || iframe.contentWindow.document;
var elem = innerDoc.getElementsByClassName("myclass")[0];

Main page is test1.ru, iframe is test2.ru (both on my computer). In .htaccess is

Header add Access-Control-Allow-Origin "http://test1.ru/2"
Header add Access-Control-Allow-Headers "origin, x-requested-with, content-type"
Header add Access-Control-Allow-Methods "PUT, GET, POST, DELETE, OPTIONS"
Header add Access-Control-Expose-Headers "X-InlineCount"

Is it possible to get inside the iframe module? I am owner of this web sites (do some testing) and can also add any settings to my firefox. What I found also that this code do not work in IE (even that I turn on acceess beween different domains and XSS filter is turned off). Chrome looks like do not support --disable-web-security anymore... Chrome's error is Blocked a frame with origin "test1" from accessing a frame with origin "test2". Protocols, domains, and ports must match.

Any ideas will be very helpful to do this.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can't directly access frames across origins. In modern browsers you can use postMessage.

The frame sending the data needs to call postMessage

top.postMessage({ foo: "bar" }, "*");

and the frame receiving the data needs to register an event listener to look for messages and react to them.

window.addEventListener("message", receiveMessage, false);
function receiveMessage(evt) {
    alert(event.data.foo);
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...