• Register
0 votes
1.7k 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!";
    });
});
6 5 3
7,540 points

Please log in or register to answer this question.

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,

9 7 4
38,600 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; 
    } 
}); 

 

10 6 4
31,120 points

Related questions

0 votes
1 answer 81 views
81 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 16 views
16 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 Jul 2, 2020 Raphael Pacheco 4.9k points
0 votes
1 answer 14 views
14 views
Problem: I am very new to programming. Now days I am trying to load the 3D model into the Three.js with a JSONLoader and that particular 3D model is in a same directory as my entire website. Still I am receiving below error: "Cross origin requests are only supported for HTTP." I am unable to know why am I receiving the above error and I am struggling to resolve it.
asked Aug 12, 2020 Raphael Pacheco 4.9k points
0 votes
1 answer 14 views
14 views
How come this code throws an when it was OK before? $(document).ready(function() { $('#tabs > ul').tabs({ fx: { opacity: 'toggle' } }); $('#featuredvid > ul').tabs(); }); Results in tabs don't close anymore. jQuery is referenced in the header: < ... <script language="JavaScript" type="text/javascript" src="<?php echo get_option('siteurl') ?>/js/jquery-ui-personalized-1.5.2.packed.js"></script>
asked Nov 10, 2020 Han Li 710 points
0 votes
1 answer 196 views
196 views
Problem: I am unable to fix the below listed Datatables error: "SCRIPT5007: Unable to set property '_DT_CellIndex' of undefined or null reference." I have already tried to look for the solution all over the internet and but unable to find the best solution for my ... am currently unable to fix this issue. Is there anything which I am missing here? Please Note: I am very newbie with JavaScript.
asked Jul 16, 2020 Raphael Pacheco 4.9k points
0 votes
1 answer 361 views
361 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 Jul 4, 2020 Raphael Pacheco 4.9k points