• Register
search
Log In
0 votes
450 views

Problem :

Uncaught domexception: blocked a frame with origin from accessing a cross-origin frame:I am trying to load the <iframe> in my HTML page and want to access the elements within it using the Javascript, however when I want to execute my code, I face the below error:

SecurityError: Blocked a frame with origin "http://www.<domain>.com" from accessing a cross-origin frame.

Can anyone help me to find the solution so that I can try to access the elements in the iframe?

I am using following code for testing but it is not working:

$(document).ready(function() {
var my iframeWindow = document.getElementById("my-iframe-id").contentWindow;
my iframeWindow.addEventListener("load", function() {
var mydoc = iframe.contentDocument || iframe.contentWindow.document;
var mytarget = mydoc.getElementById("my-target-id");
mytarget.innerHTML = "Found it!";
    });
});
7.5k points

2 Answers

0 votes

Solution :

The same-origin policy:

Because of same-origin policy you can not access the <iframe> with the different origin using JavaScript, it will be the huge security flaw if anybody could do it. For the same-origin policy browsers do block scripts which are trying to access the iframe with a different origin.

The origin can be considered as different if at least one of the below parts of the address is not maintained:

<protocol>://<hostname>:<port>/path/to/page.html 

If you want to access a frame then your Protocolhostname and port must be the same for your domain,

Even if the same-origin policy is blocking your scripts from accessing the content of your sites with a different origin but if you own both the pages then you can work around this problem using window.postMessage and it is relative message event to send the messages between your two pages,

36.1k points
0 votes

Solution:

Same-origin policy

You can't access an <iframe> with different origin employing JavaScript, it would be a huge security flaw in case you could do it. For the same-origin policy browsers block scripts attempting to access a frame with a different origin.

Origin is considered different in case at least one of the following parts of the address isn't maintained:

<protocol>://<hostname>:<port>/...

Protocol, hostname and port should be the similar of your domain, in case you want to access a frame.

Examples

Here's what would occur attempting to access the following URLs from

http://www.example.com/home/index.html

URL                                             RESULT 
http://www.example.com/home/other.html       -> Success 
http://www.example.com/dir/inner/another.php -> Success 
http://www.example.com:80                    -> Success (default port for HTTP) 
http://www.example.com:2251                  -> Failure: different port 
http://data.example.com/dir/other.html       -> Failure: different hostname 
https://www.example.com/home/index.html:80   -> Failure: different protocol
ftp://www.example.com:21                     -> Failure: different protocol & port 
https://google.com/search?q=james+bond       -> Failure: different protocol, port & hostname 

Workaround

Even though same-origin policy blocks scripts from accessing the content of sites with a different origin, in case you own both the pages, you can perform around this problem employing window.postMessage and its relative message event to send messages between the two pages, like this:

In your main page:

let frame = document.getElementById('your-frame-id');
frame.contentWindow.postMessage(/*any variable or object here*/, 'http://your-second-site.com');

The second argument to postMessage() can be '*' to indicate no preference regarding the origin of the destination. A target origin must always be provided when possible, to fudge disclosing the data you send to any other site.

In your <iframe> (contained in the main page):

window.addEventListener('message', event => {
    // IMPORTANT: check the origin of the data! 
    if (event.origin.startsWith('http://your-first-site.com')) { 
        // The data was sent from your site.
        // Data sent with postMessage is stored in event.data:
        console.log(event.data); 
    } else {
        // The data was NOT sent from your site! 
        // Be careful! Do not use it. This else branch is
        // here just for clarity, you usually shouldn't need it.
        return; 
    } 
}); 

This method can be employed in both directions, making a listener in the main page too, and taking responses from the frame. The similar logic can also be executed in pop-ups and originally any new window produced by the main page (for examle employing window.open()) as well, without any difference.

Disabling same-origin policy in your browser

There meanwhile are some good answers regarding this topic. Hence, for the browsers where this is possible, I'll link the comparative answer. But, please remember that disabling the same-origin policy will just affect your browser. Further, running a browser with same-origin security settings disabled grants any website access to cross-origin resources, hence it's very unsafe and must NEVER be done in case you do not know accurately what you are doing (for example development purposes).

In your main page:

var frame = document.getElementById('your-frame-id'); 

frame.contentWindow.postMessage(/*any variable or object here*/, '*'); 

In your <iframe> (contained in the main page):

window.addEventListener('message', function(event) { 

    // IMPORTANT: Check the origin of the data! 
    if (~event.origin.indexOf('http://yoursite.com')) { 
        // The data has been sent from your site 

        // The data sent with postMessage is stored in event.data 
        console.log(event.data); 
    } else { 
        // The data hasn't been sent from your site! 
        // Be careful! Do not use it. 
        return; 
    } 
}); 

 

12.8k points
edited by

Related questions

0 votes
1 answer 50 views
50 views
Problem : I am getting following error cross-origin request blocked: the same origin policy disallows reading the remote resource at
asked Nov 15, 2019 peterlaw 6.9k points
0 votes
1 answer 6 views
6 views
Problem: I want to create the search box for the states, districts and villages but because of some unknown reason to me I am just unable to fetch my data into the combobox. Please find my code as shown below: My HTML code: <div class="dummy__item">  < ... below task: Dynamically populate a select element from json data with jquery . I am looking for the expert in Javascript , Jquery and Json.
asked 6 days ago Raphael Pacheco 680 points
0 votes
1 answer 28 views
28 views
Problem : I want to send a call using ajax but in Chrome getting following error Failed to load resource: the server responded with a status of 500 (internal server error) But for firefox getting no error. I also tried to record the ajax call in firebug but there is no call request in ... function (msg) { }, error: function (xhr, status, error) { alert(error.responseTextss); } }); }); }); }); }
asked Nov 22, 2019 peterlaw 6.9k points
0 votes
1 answer 5 views
5 views
Problem: I have fundamental knowledge in PHP. Recently I have written a php code for bootstrap collapse but I am facing the error as below: "Cannot read property 'querySelectorAll' of null." I have spent a huge amount of time to this very simple problem. If I try ... js:378) at Function.each (jquery.js:368) at jQuery.fn.init.each (jquery.js:157) at HTMLButtonElement.<anonymous> (collapse.js:374)
asked 4 days ago Raphael Pacheco 680 points
1 vote
1 answer 44 views
44 views
Problem: I have elementary knowledge of Jquery and Javascript. Currently I am working on the pagination and I am trying to use the DataTables plugin. I have observed that on some of the tables it works as expected but on some of my tables it gives below error: " ... it is very common error but I am unable to find anything related to my problem. Kindly help me if any Jquery expert is around.
asked Jun 2 Martin K 6.6k points