Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cross domain iframe issue

For say i have a Site called example.com on which iframe is embedded of domain iframe.net, now i want to read the content of iframe and pass some parameter to display a textual message. Like Hi with username.

Now the problem is this able not able to make connection between the two , even am not able to get the innerHTML of iframe i used following approach

document.getElementById('myframe').contentWindow.document.body.innerHTML; 

It throws error "Permission denied to access property"

Do anyone know how to read and write in cross domain platform

like image 683
Kunal Vashist Avatar asked Feb 22 '12 11:02

Kunal Vashist


People also ask

Can I load an iframe from a different domain?

Generally, web application allows script running between pages(parent and iframe pages) in the same domain based on same-origin-policy. Unfortunately it does not support scripts if different domain. The policy does not allow it.

How do you know if an iframe is cross domain?

to select the iframe with querySelector . Then we define the canAccessIFrame function that checks if the iframe has the contentDocument property defined. If it's defined then it's not a cross-domain iframe or it's cross domain and cross domain is allowed. Otherwise, false is returned.

How do I fix refused connection in iframe?

You cannot fix this from Power Apps Portal side. Most probably web site that you try to embed as an iframe doesn't allow to be embedded. You need to update X-Frame-Options on the website that you are trying to embed to allow your Power Apps Portal (if you have control over that website).


2 Answers

If you don't have control over the framed site, you cannot circumvent the cross-domain policy.

If you have control over both sites, you can use the postMessage method to transfer data across different domains. A very basic example:

// framed.htm: window.onmessage = function(event) {     event.source.postMessage(document.body.innerHTML, event.origin); };  // Main page: window.onmessage = function(event) {     alert(event.data); };  // Trigger: // <iframe id="myframe" src="framed.htm"></iframe> document.getElementById('myframe').contentWindow.postMessage('','*'); 
like image 90
Rob W Avatar answered Oct 02 '22 00:10

Rob W


In Internet Explorer 8, events passed as a parameter may be null, that is why you need to access the event in a different manner:

In frame.html:

window.onmessage = function(event) {    var evt = event || window.event;    evt.source.postMessage('Message from iFrame', evt.origin); }; 

On main.html:

window.onmessage = function(event) {    var evt = event || window.event;    alert(evt.data); }; 

The event is triggered the same way as Rob W has presented:

document.getElementById('frameId').contentWindow.postMessage('message','*'); 
like image 20
Przemek Marcinkiewicz Avatar answered Oct 02 '22 01:10

Przemek Marcinkiewicz