SecurityError: Blocked a frame with origin from accessing a cross-origin frame Announcing the arrival of Valued Associate #679: Cesar Manara Planned maintenance scheduled April 23, 2019 at 23:30 UTC (7:30 pm US/Eastern) Data science time! April 2019 and salary with experience The Ask Question Wizard is Live!how to allow cross-origin frameHow to click a button inside iframe using JavaScriptBlocked a frame with origin “http://localhost”Can't execute JavaScript cross origin, cross frameIs there a way to ignore same-origin policy for web pages served locally (file:///)JS cross domainIs it possible to host an iframe in one domain and target it to a different domain?get javascript code from iframeOAuth 2.0 Implicit flow with React without a backendGet instagram image src from Embed with querySelectorjQuery .ready in a dynamically inserted iframeWhy does my JavaScript get a “No 'Access-Control-Allow-Origin' header is present on the requested resource” error when Postman does not?Youtube - SecurityError: Blocked a frame with origin “null” from accessing a cross-origin frameHow to avoid Uncaught SecurityError: Blocked a frame with origin with phonegapBlocked a frame with origin “http://localhost:8084” from accessing a cross-origin frameBlocked a frame with origin from accessing a cross-origin frame. I own both the websiteGWT Blocked a frame with origin “http://localhost” from accessing a cross-origin frameChrome Extension - Uncaught DOMException: Blocked a frame with origin from accessing a cross-origin frameSymfony 1.4 - SecurityError: Blocked a frame with origin “[url]” from accessing a cross-origin frameBlocked a frame with origin “https://example.com” from accessing a cross-origin frame

What's parked in Mil Moscow helicopter plant?

What do you call an IPA symbol that lacks a name (e.g. ɲ)?

How do I deal with an erroneously large refund?

Why did Israel vote against lifting the American embargo on Cuba?

What were wait-states, and why was it only an issue for PCs?

What does the black goddess statue do and what is it?

Test if all elements of a Foldable are the same

When I export an AI 300x60 art board it saves with bigger dimensions

Is it appropriate to mention a relatable company blog post when you're asked about the company?

Is a self contained air-bullet cartridge feasible?

All ASCII characters with a given bit count

Bright yellow or light yellow?

Like totally amazing interchangeable sister outfit accessory swapping or whatever

Married in secret, can marital status in passport be changed at a later date?

Could a cockatrice have parasitic embryos?

How to keep bees out of canned beverages?

What is the term for extremely loose Latin word order?

What's called a person who works as someone who puts products on shelves in stores?

Where to find documentation for `whois` command options?

Protagonist's race is hidden - should I reveal it?

What *exactly* is electrical current, voltage, and resistance?

What is the purpose of the side handle on a hand ("eggbeater") drill?

Is Bran literally the world's memory?

France's Public Holidays' Puzzle



SecurityError: Blocked a frame with origin from accessing a cross-origin frame



Announcing the arrival of Valued Associate #679: Cesar Manara
Planned maintenance scheduled April 23, 2019 at 23:30 UTC (7:30 pm US/Eastern)
Data science time! April 2019 and salary with experience
The Ask Question Wizard is Live!how to allow cross-origin frameHow to click a button inside iframe using JavaScriptBlocked a frame with origin “http://localhost”Can't execute JavaScript cross origin, cross frameIs there a way to ignore same-origin policy for web pages served locally (file:///)JS cross domainIs it possible to host an iframe in one domain and target it to a different domain?get javascript code from iframeOAuth 2.0 Implicit flow with React without a backendGet instagram image src from Embed with querySelectorjQuery .ready in a dynamically inserted iframeWhy does my JavaScript get a “No 'Access-Control-Allow-Origin' header is present on the requested resource” error when Postman does not?Youtube - SecurityError: Blocked a frame with origin “null” from accessing a cross-origin frameHow to avoid Uncaught SecurityError: Blocked a frame with origin with phonegapBlocked a frame with origin “http://localhost:8084” from accessing a cross-origin frameBlocked a frame with origin from accessing a cross-origin frame. I own both the websiteGWT Blocked a frame with origin “http://localhost” from accessing a cross-origin frameChrome Extension - Uncaught DOMException: Blocked a frame with origin from accessing a cross-origin frameSymfony 1.4 - SecurityError: Blocked a frame with origin “[url]” from accessing a cross-origin frameBlocked a frame with origin “https://example.com” from accessing a cross-origin frame



.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;








414















I am loading an <iframe> in my HTML page and trying to access the elements within it using Javascript, but when I try to execute my code, I get the following error:



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


Can you please help me to find a solution so that I can access the elements in the frame?



I am using this code for testing, but in vain:



$(document).ready(function() 
var iframeWindow = document.getElementById("my-iframe-id").contentWindow;

iframeWindow.addEventListener("load", function() );
);









share|improve this question






























    414















    I am loading an <iframe> in my HTML page and trying to access the elements within it using Javascript, but when I try to execute my code, I get the following error:



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


    Can you please help me to find a solution so that I can access the elements in the frame?



    I am using this code for testing, but in vain:



    $(document).ready(function() 
    var iframeWindow = document.getElementById("my-iframe-id").contentWindow;

    iframeWindow.addEventListener("load", function() );
    );









    share|improve this question


























      414












      414








      414


      187






      I am loading an <iframe> in my HTML page and trying to access the elements within it using Javascript, but when I try to execute my code, I get the following error:



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


      Can you please help me to find a solution so that I can access the elements in the frame?



      I am using this code for testing, but in vain:



      $(document).ready(function() 
      var iframeWindow = document.getElementById("my-iframe-id").contentWindow;

      iframeWindow.addEventListener("load", function() );
      );









      share|improve this question
















      I am loading an <iframe> in my HTML page and trying to access the elements within it using Javascript, but when I try to execute my code, I get the following error:



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


      Can you please help me to find a solution so that I can access the elements in the frame?



      I am using this code for testing, but in vain:



      $(document).ready(function() 
      var iframeWindow = document.getElementById("my-iframe-id").contentWindow;

      iframeWindow.addEventListener("load", function() );
      );






      javascript jquery iframe same-origin-policy






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Dec 7 '15 at 14:30









      Marco Bonelli

      24.1k116475




      24.1k116475










      asked Aug 2 '14 at 18:14









      mubashermubimubashermubi

      2,38131223




      2,38131223






















          5 Answers
          5






          active

          oldest

          votes


















          631














          Same-origin policy



          Not to be confused with CORS!



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



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



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


          Protocol, hostname and port must be the same of your domain, if you want to access a frame.



          Examples



          Here's what would happen trying 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.html -> Failure: different protocol
          ftp://www.example.com:21 -> Failure: different protocol & port
          https://google.com/search?q=james+bond -> Failure: different hostname & protocol


          Workaround



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




          • 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;

            );


          This method can be applied in both directions, creating a listener in the main page too, and receiving responses from the frame. The same logic can also be implemented in pop-ups and basically any new window generated by the main page (e.g. using window.open()) as well, without any difference.



          Disabling same-origin policy in your browser



          There already are some good answers about this topic (I just found them googling), so, for the browsers where this is possible, I'll link the relative answer. However, please remember that disabling the same-origin policy (or the CORS) will only affect your browser. Also, running a browser with same-origin security settings disabled grants any website access to cross-origin resources, so it's very unsafe and should be done for development purposes only.



          • Google Chrome

          • Mozilla Firefox

          • Apple Safari: not possible, only CORS.

          • Opera: not possible.

          • Microsoft Edge: not possible.

          • Microsoft Internet Explorer: not possible, only CORS.





          share|improve this answer




















          • 20





            Any other answer I've found 1, 2, suggests that CORS/Access-Control-Allow-Origin does not apply to iFrames, only to XHRs, Fonts, WebGL and canvas.drawImage. I believe postMessage is the only option.

            – snappieT
            Jan 14 '15 at 12:12







          • 8





            i'll just leave this here github.com/ternarylabs/porthole

            – parliament
            Feb 20 '15 at 22:11






          • 328





            First time I've seen the tilde "~" operator in javascript. For anyone else who also didn't know what it does: it converts -1 to 0, which saves you having to do "!= -1" on the result of the indexOf. Personally, I think I'll carry on using "!= -1" as it's easier for other programmers to understand and avoids the bugs that would come from forgetting to put the tilde in. (But it's always nice to learn something new.)

            – Redzarf
            Jun 5 '15 at 16:32







          • 3





            @SabaAhang just check for the iframe.src, and if the site it's different from your domain's hostname then you can't access that frame.

            – Marco Bonelli
            Oct 17 '15 at 9:34






          • 11





            @Snuggs totally wrong, ~ returns the 2's complement of the number, so n becomes -n-1, meaning that only -1 will become 0 (which is interpreted as false), and any other value will pass the test. I.E. 0 = -(-1)-1, not -(-1+1).

            – Marco Bonelli
            Nov 8 '16 at 6:18



















          46














          Complementing Marco Bonelli's answer: the best current way of interacting between frames/iframes is using window.postMessage, supported by all browsers






          share|improve this answer




















          • 18





            While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference. Link-only answers can become invalid if the linked page changes. - From Review

            – Alessandro Cuttin
            Apr 1 '16 at 15:30






          • 7





            I disagree, @AlessandroCuttin. Explaining how window.postMessage works would only duplicate the accepted answer which I already reference. Furthermore, the essential value my answer adds is exactly that of referencing external documentation.

            – Geert
            Apr 4 '16 at 12:42






          • 3





            I think its a better if you can edit the accepted answer and add it there

            – Martin Massera
            Jan 3 '17 at 4:17






          • 8





            window.postMessage we can use only if we can able to access both parent(our HTML page) and children element(other domain iframe).Otherwise "THERE IS NO POSSIBILITY", it will always throws an error "Uncaught DOMException: Blocked a frame with origin "<yourdomainname.com>" from accessing a cross-origin frame."

            – VIJAY P
            Feb 1 '17 at 18:35



















          11














          Check the domain's web server for http://www.<domain>.com configuration for X-Frame-Options
          It is a security feature designed to prevent clickJacking attacks,



          How Does clickJacking work?



          1. The evil page looks exactly like the victim page.

          2. Then it tricked users to enter their username and password.

          Technically the evil has an iframe with the source to the victim page.



          <html>
          <iframe src='victim_domain.com'/>
          <input id="username" type="text" style="display: none;/>
          <input id="password" type="text" style="display: none;/>
          <script>
          //some JS code that click jacking the user username and input from inside the iframe...
          <script/>
          <html>


          How the security feature work



          If you want to prevent web server request to be rendered within an iframe add the x-frame-options




          X-Frame-Options DENY




          The options are:



          1. SAMEORIGIN //allow only to my own domain render my HTML inside an iframe.

          2. DENY //do not allow my HTML to be rendered inside any iframe

          3. "ALLOW-FROM https://example.com/" //allow specific domain to render my HTML inside an iframe

          This is IIS config example:



           <httpProtocol>
          <customHeaders>
          <add name="X-Frame-Options" value="SAMEORIGIN" />
          </customHeaders>
          </httpProtocol>


          The solution to the question



          If the web server activated the security feature it may cause a client-side SecurityError as it should.






          share|improve this answer
































            6














            For me i wanted to implement a 2-way handshake, meaning:

            - the parent window will load faster then the iframe

            - the iframe should talk to the parent window as soon as its ready

            - the parent is ready to receive the iframe message and replay



            this code is used to set white label in the iframe using [CSS custom property]

            code:
            iframe



            $(function() 
            window.onload = function()
            // create listener
            function receiveMessage(e)
            document.documentElement.style.setProperty('--header_bg', e.data.wl.header_bg);
            document.documentElement.style.setProperty('--header_text', e.data.wl.header_text);
            document.documentElement.style.setProperty('--button_bg', e.data.wl.button_bg);
            //alert(e.data.data.header_bg);

            window.addEventListener('message', receiveMessage);
            // call parent
            parent.postMessage("GetWhiteLabel","*");

            );


            parent



            $(function() 
            // create listener
            var eventMethod = window.addEventListener ? "addEventListener" : "attachEvent";
            var eventer = window[eventMethod];
            var messageEvent = eventMethod == "attachEvent" ? "onmessage" : "message";
            eventer(messageEvent, function (e)
            // replay to child (iframe)
            document.getElementById('wrapper-iframe').contentWindow.postMessage(

            event_id: 'white_label_message',
            wl:
            header_bg: $('#Header').css('background-color'),
            header_text: $('#Header .HoverMenu a').css('color'),
            button_bg: $('#Header .HoverMenu a').css('background-color')

            ,
            '*'
            );
            , false);
            );


            naturally you can limit the origins and the text, this is easy-to-work-with code

            i found this examlpe to be helpful:
            [Cross-Domain Messaging With postMessage]






            share|improve this answer

























            • i'm dealing with an issue with safari where document in iframe is executing its JS later than parent page which causes the message to be sent earlier than document in iframe is listening to messages; which is exactly opposite from what chrome and firefox do - have you tested your code in safari on ios? btw postMessage with second parameter of value "*" is not quite safe, you should always specify domain

              – sKopheK
              Mar 22 '18 at 15:51












            • Your first block of code, is that on the iframe in the parent or is it on the page that gets loaded into the iframe ?

              – Demonic218
              Feb 15 at 9:45


















            -6














            • Open the start menu

            • Type windows+R or open "Run

            • Execute the following command.

            chrome.exe --user-data-dir="C://Chrome dev session" --disable-web-security






            share|improve this answer




















            • 1





              Good for quick and dirty test!

              – user1068352
              Oct 16 '18 at 22:05











            • Terrible for anything that is not a quick and dirty test … and already address in the accepted answer.

              – Quentin
              Mar 26 at 11:23









            protected by Community Nov 3 '15 at 12:20



            Thank you for your interest in this question.
            Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).



            Would you like to answer one of these unanswered questions instead?














            5 Answers
            5






            active

            oldest

            votes








            5 Answers
            5






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            631














            Same-origin policy



            Not to be confused with CORS!



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



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



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


            Protocol, hostname and port must be the same of your domain, if you want to access a frame.



            Examples



            Here's what would happen trying 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.html -> Failure: different protocol
            ftp://www.example.com:21 -> Failure: different protocol & port
            https://google.com/search?q=james+bond -> Failure: different hostname & protocol


            Workaround



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




            • 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;

              );


            This method can be applied in both directions, creating a listener in the main page too, and receiving responses from the frame. The same logic can also be implemented in pop-ups and basically any new window generated by the main page (e.g. using window.open()) as well, without any difference.



            Disabling same-origin policy in your browser



            There already are some good answers about this topic (I just found them googling), so, for the browsers where this is possible, I'll link the relative answer. However, please remember that disabling the same-origin policy (or the CORS) will only affect your browser. Also, running a browser with same-origin security settings disabled grants any website access to cross-origin resources, so it's very unsafe and should be done for development purposes only.



            • Google Chrome

            • Mozilla Firefox

            • Apple Safari: not possible, only CORS.

            • Opera: not possible.

            • Microsoft Edge: not possible.

            • Microsoft Internet Explorer: not possible, only CORS.





            share|improve this answer




















            • 20





              Any other answer I've found 1, 2, suggests that CORS/Access-Control-Allow-Origin does not apply to iFrames, only to XHRs, Fonts, WebGL and canvas.drawImage. I believe postMessage is the only option.

              – snappieT
              Jan 14 '15 at 12:12







            • 8





              i'll just leave this here github.com/ternarylabs/porthole

              – parliament
              Feb 20 '15 at 22:11






            • 328





              First time I've seen the tilde "~" operator in javascript. For anyone else who also didn't know what it does: it converts -1 to 0, which saves you having to do "!= -1" on the result of the indexOf. Personally, I think I'll carry on using "!= -1" as it's easier for other programmers to understand and avoids the bugs that would come from forgetting to put the tilde in. (But it's always nice to learn something new.)

              – Redzarf
              Jun 5 '15 at 16:32







            • 3





              @SabaAhang just check for the iframe.src, and if the site it's different from your domain's hostname then you can't access that frame.

              – Marco Bonelli
              Oct 17 '15 at 9:34






            • 11





              @Snuggs totally wrong, ~ returns the 2's complement of the number, so n becomes -n-1, meaning that only -1 will become 0 (which is interpreted as false), and any other value will pass the test. I.E. 0 = -(-1)-1, not -(-1+1).

              – Marco Bonelli
              Nov 8 '16 at 6:18
















            631














            Same-origin policy



            Not to be confused with CORS!



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



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



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


            Protocol, hostname and port must be the same of your domain, if you want to access a frame.



            Examples



            Here's what would happen trying 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.html -> Failure: different protocol
            ftp://www.example.com:21 -> Failure: different protocol & port
            https://google.com/search?q=james+bond -> Failure: different hostname & protocol


            Workaround



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




            • 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;

              );


            This method can be applied in both directions, creating a listener in the main page too, and receiving responses from the frame. The same logic can also be implemented in pop-ups and basically any new window generated by the main page (e.g. using window.open()) as well, without any difference.



            Disabling same-origin policy in your browser



            There already are some good answers about this topic (I just found them googling), so, for the browsers where this is possible, I'll link the relative answer. However, please remember that disabling the same-origin policy (or the CORS) will only affect your browser. Also, running a browser with same-origin security settings disabled grants any website access to cross-origin resources, so it's very unsafe and should be done for development purposes only.



            • Google Chrome

            • Mozilla Firefox

            • Apple Safari: not possible, only CORS.

            • Opera: not possible.

            • Microsoft Edge: not possible.

            • Microsoft Internet Explorer: not possible, only CORS.





            share|improve this answer




















            • 20





              Any other answer I've found 1, 2, suggests that CORS/Access-Control-Allow-Origin does not apply to iFrames, only to XHRs, Fonts, WebGL and canvas.drawImage. I believe postMessage is the only option.

              – snappieT
              Jan 14 '15 at 12:12







            • 8





              i'll just leave this here github.com/ternarylabs/porthole

              – parliament
              Feb 20 '15 at 22:11






            • 328





              First time I've seen the tilde "~" operator in javascript. For anyone else who also didn't know what it does: it converts -1 to 0, which saves you having to do "!= -1" on the result of the indexOf. Personally, I think I'll carry on using "!= -1" as it's easier for other programmers to understand and avoids the bugs that would come from forgetting to put the tilde in. (But it's always nice to learn something new.)

              – Redzarf
              Jun 5 '15 at 16:32







            • 3





              @SabaAhang just check for the iframe.src, and if the site it's different from your domain's hostname then you can't access that frame.

              – Marco Bonelli
              Oct 17 '15 at 9:34






            • 11





              @Snuggs totally wrong, ~ returns the 2's complement of the number, so n becomes -n-1, meaning that only -1 will become 0 (which is interpreted as false), and any other value will pass the test. I.E. 0 = -(-1)-1, not -(-1+1).

              – Marco Bonelli
              Nov 8 '16 at 6:18














            631












            631








            631







            Same-origin policy



            Not to be confused with CORS!



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



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



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


            Protocol, hostname and port must be the same of your domain, if you want to access a frame.



            Examples



            Here's what would happen trying 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.html -> Failure: different protocol
            ftp://www.example.com:21 -> Failure: different protocol & port
            https://google.com/search?q=james+bond -> Failure: different hostname & protocol


            Workaround



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




            • 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;

              );


            This method can be applied in both directions, creating a listener in the main page too, and receiving responses from the frame. The same logic can also be implemented in pop-ups and basically any new window generated by the main page (e.g. using window.open()) as well, without any difference.



            Disabling same-origin policy in your browser



            There already are some good answers about this topic (I just found them googling), so, for the browsers where this is possible, I'll link the relative answer. However, please remember that disabling the same-origin policy (or the CORS) will only affect your browser. Also, running a browser with same-origin security settings disabled grants any website access to cross-origin resources, so it's very unsafe and should be done for development purposes only.



            • Google Chrome

            • Mozilla Firefox

            • Apple Safari: not possible, only CORS.

            • Opera: not possible.

            • Microsoft Edge: not possible.

            • Microsoft Internet Explorer: not possible, only CORS.





            share|improve this answer















            Same-origin policy



            Not to be confused with CORS!



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



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



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


            Protocol, hostname and port must be the same of your domain, if you want to access a frame.



            Examples



            Here's what would happen trying 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.html -> Failure: different protocol
            ftp://www.example.com:21 -> Failure: different protocol & port
            https://google.com/search?q=james+bond -> Failure: different hostname & protocol


            Workaround



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




            • 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;

              );


            This method can be applied in both directions, creating a listener in the main page too, and receiving responses from the frame. The same logic can also be implemented in pop-ups and basically any new window generated by the main page (e.g. using window.open()) as well, without any difference.



            Disabling same-origin policy in your browser



            There already are some good answers about this topic (I just found them googling), so, for the browsers where this is possible, I'll link the relative answer. However, please remember that disabling the same-origin policy (or the CORS) will only affect your browser. Also, running a browser with same-origin security settings disabled grants any website access to cross-origin resources, so it's very unsafe and should be done for development purposes only.



            • Google Chrome

            • Mozilla Firefox

            • Apple Safari: not possible, only CORS.

            • Opera: not possible.

            • Microsoft Edge: not possible.

            • Microsoft Internet Explorer: not possible, only CORS.






            share|improve this answer














            share|improve this answer



            share|improve this answer








            edited Mar 26 at 11:16

























            answered Aug 2 '14 at 18:28









            Marco BonelliMarco Bonelli

            24.1k116475




            24.1k116475







            • 20





              Any other answer I've found 1, 2, suggests that CORS/Access-Control-Allow-Origin does not apply to iFrames, only to XHRs, Fonts, WebGL and canvas.drawImage. I believe postMessage is the only option.

              – snappieT
              Jan 14 '15 at 12:12







            • 8





              i'll just leave this here github.com/ternarylabs/porthole

              – parliament
              Feb 20 '15 at 22:11






            • 328





              First time I've seen the tilde "~" operator in javascript. For anyone else who also didn't know what it does: it converts -1 to 0, which saves you having to do "!= -1" on the result of the indexOf. Personally, I think I'll carry on using "!= -1" as it's easier for other programmers to understand and avoids the bugs that would come from forgetting to put the tilde in. (But it's always nice to learn something new.)

              – Redzarf
              Jun 5 '15 at 16:32







            • 3





              @SabaAhang just check for the iframe.src, and if the site it's different from your domain's hostname then you can't access that frame.

              – Marco Bonelli
              Oct 17 '15 at 9:34






            • 11





              @Snuggs totally wrong, ~ returns the 2's complement of the number, so n becomes -n-1, meaning that only -1 will become 0 (which is interpreted as false), and any other value will pass the test. I.E. 0 = -(-1)-1, not -(-1+1).

              – Marco Bonelli
              Nov 8 '16 at 6:18













            • 20





              Any other answer I've found 1, 2, suggests that CORS/Access-Control-Allow-Origin does not apply to iFrames, only to XHRs, Fonts, WebGL and canvas.drawImage. I believe postMessage is the only option.

              – snappieT
              Jan 14 '15 at 12:12







            • 8





              i'll just leave this here github.com/ternarylabs/porthole

              – parliament
              Feb 20 '15 at 22:11






            • 328





              First time I've seen the tilde "~" operator in javascript. For anyone else who also didn't know what it does: it converts -1 to 0, which saves you having to do "!= -1" on the result of the indexOf. Personally, I think I'll carry on using "!= -1" as it's easier for other programmers to understand and avoids the bugs that would come from forgetting to put the tilde in. (But it's always nice to learn something new.)

              – Redzarf
              Jun 5 '15 at 16:32







            • 3





              @SabaAhang just check for the iframe.src, and if the site it's different from your domain's hostname then you can't access that frame.

              – Marco Bonelli
              Oct 17 '15 at 9:34






            • 11





              @Snuggs totally wrong, ~ returns the 2's complement of the number, so n becomes -n-1, meaning that only -1 will become 0 (which is interpreted as false), and any other value will pass the test. I.E. 0 = -(-1)-1, not -(-1+1).

              – Marco Bonelli
              Nov 8 '16 at 6:18








            20




            20





            Any other answer I've found 1, 2, suggests that CORS/Access-Control-Allow-Origin does not apply to iFrames, only to XHRs, Fonts, WebGL and canvas.drawImage. I believe postMessage is the only option.

            – snappieT
            Jan 14 '15 at 12:12






            Any other answer I've found 1, 2, suggests that CORS/Access-Control-Allow-Origin does not apply to iFrames, only to XHRs, Fonts, WebGL and canvas.drawImage. I believe postMessage is the only option.

            – snappieT
            Jan 14 '15 at 12:12





            8




            8





            i'll just leave this here github.com/ternarylabs/porthole

            – parliament
            Feb 20 '15 at 22:11





            i'll just leave this here github.com/ternarylabs/porthole

            – parliament
            Feb 20 '15 at 22:11




            328




            328





            First time I've seen the tilde "~" operator in javascript. For anyone else who also didn't know what it does: it converts -1 to 0, which saves you having to do "!= -1" on the result of the indexOf. Personally, I think I'll carry on using "!= -1" as it's easier for other programmers to understand and avoids the bugs that would come from forgetting to put the tilde in. (But it's always nice to learn something new.)

            – Redzarf
            Jun 5 '15 at 16:32






            First time I've seen the tilde "~" operator in javascript. For anyone else who also didn't know what it does: it converts -1 to 0, which saves you having to do "!= -1" on the result of the indexOf. Personally, I think I'll carry on using "!= -1" as it's easier for other programmers to understand and avoids the bugs that would come from forgetting to put the tilde in. (But it's always nice to learn something new.)

            – Redzarf
            Jun 5 '15 at 16:32





            3




            3





            @SabaAhang just check for the iframe.src, and if the site it's different from your domain's hostname then you can't access that frame.

            – Marco Bonelli
            Oct 17 '15 at 9:34





            @SabaAhang just check for the iframe.src, and if the site it's different from your domain's hostname then you can't access that frame.

            – Marco Bonelli
            Oct 17 '15 at 9:34




            11




            11





            @Snuggs totally wrong, ~ returns the 2's complement of the number, so n becomes -n-1, meaning that only -1 will become 0 (which is interpreted as false), and any other value will pass the test. I.E. 0 = -(-1)-1, not -(-1+1).

            – Marco Bonelli
            Nov 8 '16 at 6:18






            @Snuggs totally wrong, ~ returns the 2's complement of the number, so n becomes -n-1, meaning that only -1 will become 0 (which is interpreted as false), and any other value will pass the test. I.E. 0 = -(-1)-1, not -(-1+1).

            – Marco Bonelli
            Nov 8 '16 at 6:18














            46














            Complementing Marco Bonelli's answer: the best current way of interacting between frames/iframes is using window.postMessage, supported by all browsers






            share|improve this answer




















            • 18





              While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference. Link-only answers can become invalid if the linked page changes. - From Review

              – Alessandro Cuttin
              Apr 1 '16 at 15:30






            • 7





              I disagree, @AlessandroCuttin. Explaining how window.postMessage works would only duplicate the accepted answer which I already reference. Furthermore, the essential value my answer adds is exactly that of referencing external documentation.

              – Geert
              Apr 4 '16 at 12:42






            • 3





              I think its a better if you can edit the accepted answer and add it there

              – Martin Massera
              Jan 3 '17 at 4:17






            • 8





              window.postMessage we can use only if we can able to access both parent(our HTML page) and children element(other domain iframe).Otherwise "THERE IS NO POSSIBILITY", it will always throws an error "Uncaught DOMException: Blocked a frame with origin "<yourdomainname.com>" from accessing a cross-origin frame."

              – VIJAY P
              Feb 1 '17 at 18:35
















            46














            Complementing Marco Bonelli's answer: the best current way of interacting between frames/iframes is using window.postMessage, supported by all browsers






            share|improve this answer




















            • 18





              While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference. Link-only answers can become invalid if the linked page changes. - From Review

              – Alessandro Cuttin
              Apr 1 '16 at 15:30






            • 7





              I disagree, @AlessandroCuttin. Explaining how window.postMessage works would only duplicate the accepted answer which I already reference. Furthermore, the essential value my answer adds is exactly that of referencing external documentation.

              – Geert
              Apr 4 '16 at 12:42






            • 3





              I think its a better if you can edit the accepted answer and add it there

              – Martin Massera
              Jan 3 '17 at 4:17






            • 8





              window.postMessage we can use only if we can able to access both parent(our HTML page) and children element(other domain iframe).Otherwise "THERE IS NO POSSIBILITY", it will always throws an error "Uncaught DOMException: Blocked a frame with origin "<yourdomainname.com>" from accessing a cross-origin frame."

              – VIJAY P
              Feb 1 '17 at 18:35














            46












            46








            46







            Complementing Marco Bonelli's answer: the best current way of interacting between frames/iframes is using window.postMessage, supported by all browsers






            share|improve this answer















            Complementing Marco Bonelli's answer: the best current way of interacting between frames/iframes is using window.postMessage, supported by all browsers







            share|improve this answer














            share|improve this answer



            share|improve this answer








            edited Dec 16 '14 at 8:19

























            answered Oct 9 '14 at 14:00









            GeertGeert

            1,7401515




            1,7401515







            • 18





              While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference. Link-only answers can become invalid if the linked page changes. - From Review

              – Alessandro Cuttin
              Apr 1 '16 at 15:30






            • 7





              I disagree, @AlessandroCuttin. Explaining how window.postMessage works would only duplicate the accepted answer which I already reference. Furthermore, the essential value my answer adds is exactly that of referencing external documentation.

              – Geert
              Apr 4 '16 at 12:42






            • 3





              I think its a better if you can edit the accepted answer and add it there

              – Martin Massera
              Jan 3 '17 at 4:17






            • 8





              window.postMessage we can use only if we can able to access both parent(our HTML page) and children element(other domain iframe).Otherwise "THERE IS NO POSSIBILITY", it will always throws an error "Uncaught DOMException: Blocked a frame with origin "<yourdomainname.com>" from accessing a cross-origin frame."

              – VIJAY P
              Feb 1 '17 at 18:35













            • 18





              While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference. Link-only answers can become invalid if the linked page changes. - From Review

              – Alessandro Cuttin
              Apr 1 '16 at 15:30






            • 7





              I disagree, @AlessandroCuttin. Explaining how window.postMessage works would only duplicate the accepted answer which I already reference. Furthermore, the essential value my answer adds is exactly that of referencing external documentation.

              – Geert
              Apr 4 '16 at 12:42






            • 3





              I think its a better if you can edit the accepted answer and add it there

              – Martin Massera
              Jan 3 '17 at 4:17






            • 8





              window.postMessage we can use only if we can able to access both parent(our HTML page) and children element(other domain iframe).Otherwise "THERE IS NO POSSIBILITY", it will always throws an error "Uncaught DOMException: Blocked a frame with origin "<yourdomainname.com>" from accessing a cross-origin frame."

              – VIJAY P
              Feb 1 '17 at 18:35








            18




            18





            While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference. Link-only answers can become invalid if the linked page changes. - From Review

            – Alessandro Cuttin
            Apr 1 '16 at 15:30





            While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference. Link-only answers can become invalid if the linked page changes. - From Review

            – Alessandro Cuttin
            Apr 1 '16 at 15:30




            7




            7





            I disagree, @AlessandroCuttin. Explaining how window.postMessage works would only duplicate the accepted answer which I already reference. Furthermore, the essential value my answer adds is exactly that of referencing external documentation.

            – Geert
            Apr 4 '16 at 12:42





            I disagree, @AlessandroCuttin. Explaining how window.postMessage works would only duplicate the accepted answer which I already reference. Furthermore, the essential value my answer adds is exactly that of referencing external documentation.

            – Geert
            Apr 4 '16 at 12:42




            3




            3





            I think its a better if you can edit the accepted answer and add it there

            – Martin Massera
            Jan 3 '17 at 4:17





            I think its a better if you can edit the accepted answer and add it there

            – Martin Massera
            Jan 3 '17 at 4:17




            8




            8





            window.postMessage we can use only if we can able to access both parent(our HTML page) and children element(other domain iframe).Otherwise "THERE IS NO POSSIBILITY", it will always throws an error "Uncaught DOMException: Blocked a frame with origin "<yourdomainname.com>" from accessing a cross-origin frame."

            – VIJAY P
            Feb 1 '17 at 18:35






            window.postMessage we can use only if we can able to access both parent(our HTML page) and children element(other domain iframe).Otherwise "THERE IS NO POSSIBILITY", it will always throws an error "Uncaught DOMException: Blocked a frame with origin "<yourdomainname.com>" from accessing a cross-origin frame."

            – VIJAY P
            Feb 1 '17 at 18:35












            11














            Check the domain's web server for http://www.<domain>.com configuration for X-Frame-Options
            It is a security feature designed to prevent clickJacking attacks,



            How Does clickJacking work?



            1. The evil page looks exactly like the victim page.

            2. Then it tricked users to enter their username and password.

            Technically the evil has an iframe with the source to the victim page.



            <html>
            <iframe src='victim_domain.com'/>
            <input id="username" type="text" style="display: none;/>
            <input id="password" type="text" style="display: none;/>
            <script>
            //some JS code that click jacking the user username and input from inside the iframe...
            <script/>
            <html>


            How the security feature work



            If you want to prevent web server request to be rendered within an iframe add the x-frame-options




            X-Frame-Options DENY




            The options are:



            1. SAMEORIGIN //allow only to my own domain render my HTML inside an iframe.

            2. DENY //do not allow my HTML to be rendered inside any iframe

            3. "ALLOW-FROM https://example.com/" //allow specific domain to render my HTML inside an iframe

            This is IIS config example:



             <httpProtocol>
            <customHeaders>
            <add name="X-Frame-Options" value="SAMEORIGIN" />
            </customHeaders>
            </httpProtocol>


            The solution to the question



            If the web server activated the security feature it may cause a client-side SecurityError as it should.






            share|improve this answer





























              11














              Check the domain's web server for http://www.<domain>.com configuration for X-Frame-Options
              It is a security feature designed to prevent clickJacking attacks,



              How Does clickJacking work?



              1. The evil page looks exactly like the victim page.

              2. Then it tricked users to enter their username and password.

              Technically the evil has an iframe with the source to the victim page.



              <html>
              <iframe src='victim_domain.com'/>
              <input id="username" type="text" style="display: none;/>
              <input id="password" type="text" style="display: none;/>
              <script>
              //some JS code that click jacking the user username and input from inside the iframe...
              <script/>
              <html>


              How the security feature work



              If you want to prevent web server request to be rendered within an iframe add the x-frame-options




              X-Frame-Options DENY




              The options are:



              1. SAMEORIGIN //allow only to my own domain render my HTML inside an iframe.

              2. DENY //do not allow my HTML to be rendered inside any iframe

              3. "ALLOW-FROM https://example.com/" //allow specific domain to render my HTML inside an iframe

              This is IIS config example:



               <httpProtocol>
              <customHeaders>
              <add name="X-Frame-Options" value="SAMEORIGIN" />
              </customHeaders>
              </httpProtocol>


              The solution to the question



              If the web server activated the security feature it may cause a client-side SecurityError as it should.






              share|improve this answer



























                11












                11








                11







                Check the domain's web server for http://www.<domain>.com configuration for X-Frame-Options
                It is a security feature designed to prevent clickJacking attacks,



                How Does clickJacking work?



                1. The evil page looks exactly like the victim page.

                2. Then it tricked users to enter their username and password.

                Technically the evil has an iframe with the source to the victim page.



                <html>
                <iframe src='victim_domain.com'/>
                <input id="username" type="text" style="display: none;/>
                <input id="password" type="text" style="display: none;/>
                <script>
                //some JS code that click jacking the user username and input from inside the iframe...
                <script/>
                <html>


                How the security feature work



                If you want to prevent web server request to be rendered within an iframe add the x-frame-options




                X-Frame-Options DENY




                The options are:



                1. SAMEORIGIN //allow only to my own domain render my HTML inside an iframe.

                2. DENY //do not allow my HTML to be rendered inside any iframe

                3. "ALLOW-FROM https://example.com/" //allow specific domain to render my HTML inside an iframe

                This is IIS config example:



                 <httpProtocol>
                <customHeaders>
                <add name="X-Frame-Options" value="SAMEORIGIN" />
                </customHeaders>
                </httpProtocol>


                The solution to the question



                If the web server activated the security feature it may cause a client-side SecurityError as it should.






                share|improve this answer















                Check the domain's web server for http://www.<domain>.com configuration for X-Frame-Options
                It is a security feature designed to prevent clickJacking attacks,



                How Does clickJacking work?



                1. The evil page looks exactly like the victim page.

                2. Then it tricked users to enter their username and password.

                Technically the evil has an iframe with the source to the victim page.



                <html>
                <iframe src='victim_domain.com'/>
                <input id="username" type="text" style="display: none;/>
                <input id="password" type="text" style="display: none;/>
                <script>
                //some JS code that click jacking the user username and input from inside the iframe...
                <script/>
                <html>


                How the security feature work



                If you want to prevent web server request to be rendered within an iframe add the x-frame-options




                X-Frame-Options DENY




                The options are:



                1. SAMEORIGIN //allow only to my own domain render my HTML inside an iframe.

                2. DENY //do not allow my HTML to be rendered inside any iframe

                3. "ALLOW-FROM https://example.com/" //allow specific domain to render my HTML inside an iframe

                This is IIS config example:



                 <httpProtocol>
                <customHeaders>
                <add name="X-Frame-Options" value="SAMEORIGIN" />
                </customHeaders>
                </httpProtocol>


                The solution to the question



                If the web server activated the security feature it may cause a client-side SecurityError as it should.







                share|improve this answer














                share|improve this answer



                share|improve this answer








                edited Sep 29 '17 at 8:41









                floydian

                6916




                6916










                answered Sep 6 '17 at 10:24









                Shahar ShokraniShahar Shokrani

                1,350727




                1,350727





















                    6














                    For me i wanted to implement a 2-way handshake, meaning:

                    - the parent window will load faster then the iframe

                    - the iframe should talk to the parent window as soon as its ready

                    - the parent is ready to receive the iframe message and replay



                    this code is used to set white label in the iframe using [CSS custom property]

                    code:
                    iframe



                    $(function() 
                    window.onload = function()
                    // create listener
                    function receiveMessage(e)
                    document.documentElement.style.setProperty('--header_bg', e.data.wl.header_bg);
                    document.documentElement.style.setProperty('--header_text', e.data.wl.header_text);
                    document.documentElement.style.setProperty('--button_bg', e.data.wl.button_bg);
                    //alert(e.data.data.header_bg);

                    window.addEventListener('message', receiveMessage);
                    // call parent
                    parent.postMessage("GetWhiteLabel","*");

                    );


                    parent



                    $(function() 
                    // create listener
                    var eventMethod = window.addEventListener ? "addEventListener" : "attachEvent";
                    var eventer = window[eventMethod];
                    var messageEvent = eventMethod == "attachEvent" ? "onmessage" : "message";
                    eventer(messageEvent, function (e)
                    // replay to child (iframe)
                    document.getElementById('wrapper-iframe').contentWindow.postMessage(

                    event_id: 'white_label_message',
                    wl:
                    header_bg: $('#Header').css('background-color'),
                    header_text: $('#Header .HoverMenu a').css('color'),
                    button_bg: $('#Header .HoverMenu a').css('background-color')

                    ,
                    '*'
                    );
                    , false);
                    );


                    naturally you can limit the origins and the text, this is easy-to-work-with code

                    i found this examlpe to be helpful:
                    [Cross-Domain Messaging With postMessage]






                    share|improve this answer

























                    • i'm dealing with an issue with safari where document in iframe is executing its JS later than parent page which causes the message to be sent earlier than document in iframe is listening to messages; which is exactly opposite from what chrome and firefox do - have you tested your code in safari on ios? btw postMessage with second parameter of value "*" is not quite safe, you should always specify domain

                      – sKopheK
                      Mar 22 '18 at 15:51












                    • Your first block of code, is that on the iframe in the parent or is it on the page that gets loaded into the iframe ?

                      – Demonic218
                      Feb 15 at 9:45















                    6














                    For me i wanted to implement a 2-way handshake, meaning:

                    - the parent window will load faster then the iframe

                    - the iframe should talk to the parent window as soon as its ready

                    - the parent is ready to receive the iframe message and replay



                    this code is used to set white label in the iframe using [CSS custom property]

                    code:
                    iframe



                    $(function() 
                    window.onload = function()
                    // create listener
                    function receiveMessage(e)
                    document.documentElement.style.setProperty('--header_bg', e.data.wl.header_bg);
                    document.documentElement.style.setProperty('--header_text', e.data.wl.header_text);
                    document.documentElement.style.setProperty('--button_bg', e.data.wl.button_bg);
                    //alert(e.data.data.header_bg);

                    window.addEventListener('message', receiveMessage);
                    // call parent
                    parent.postMessage("GetWhiteLabel","*");

                    );


                    parent



                    $(function() 
                    // create listener
                    var eventMethod = window.addEventListener ? "addEventListener" : "attachEvent";
                    var eventer = window[eventMethod];
                    var messageEvent = eventMethod == "attachEvent" ? "onmessage" : "message";
                    eventer(messageEvent, function (e)
                    // replay to child (iframe)
                    document.getElementById('wrapper-iframe').contentWindow.postMessage(

                    event_id: 'white_label_message',
                    wl:
                    header_bg: $('#Header').css('background-color'),
                    header_text: $('#Header .HoverMenu a').css('color'),
                    button_bg: $('#Header .HoverMenu a').css('background-color')

                    ,
                    '*'
                    );
                    , false);
                    );


                    naturally you can limit the origins and the text, this is easy-to-work-with code

                    i found this examlpe to be helpful:
                    [Cross-Domain Messaging With postMessage]






                    share|improve this answer

























                    • i'm dealing with an issue with safari where document in iframe is executing its JS later than parent page which causes the message to be sent earlier than document in iframe is listening to messages; which is exactly opposite from what chrome and firefox do - have you tested your code in safari on ios? btw postMessage with second parameter of value "*" is not quite safe, you should always specify domain

                      – sKopheK
                      Mar 22 '18 at 15:51












                    • Your first block of code, is that on the iframe in the parent or is it on the page that gets loaded into the iframe ?

                      – Demonic218
                      Feb 15 at 9:45













                    6












                    6








                    6







                    For me i wanted to implement a 2-way handshake, meaning:

                    - the parent window will load faster then the iframe

                    - the iframe should talk to the parent window as soon as its ready

                    - the parent is ready to receive the iframe message and replay



                    this code is used to set white label in the iframe using [CSS custom property]

                    code:
                    iframe



                    $(function() 
                    window.onload = function()
                    // create listener
                    function receiveMessage(e)
                    document.documentElement.style.setProperty('--header_bg', e.data.wl.header_bg);
                    document.documentElement.style.setProperty('--header_text', e.data.wl.header_text);
                    document.documentElement.style.setProperty('--button_bg', e.data.wl.button_bg);
                    //alert(e.data.data.header_bg);

                    window.addEventListener('message', receiveMessage);
                    // call parent
                    parent.postMessage("GetWhiteLabel","*");

                    );


                    parent



                    $(function() 
                    // create listener
                    var eventMethod = window.addEventListener ? "addEventListener" : "attachEvent";
                    var eventer = window[eventMethod];
                    var messageEvent = eventMethod == "attachEvent" ? "onmessage" : "message";
                    eventer(messageEvent, function (e)
                    // replay to child (iframe)
                    document.getElementById('wrapper-iframe').contentWindow.postMessage(

                    event_id: 'white_label_message',
                    wl:
                    header_bg: $('#Header').css('background-color'),
                    header_text: $('#Header .HoverMenu a').css('color'),
                    button_bg: $('#Header .HoverMenu a').css('background-color')

                    ,
                    '*'
                    );
                    , false);
                    );


                    naturally you can limit the origins and the text, this is easy-to-work-with code

                    i found this examlpe to be helpful:
                    [Cross-Domain Messaging With postMessage]






                    share|improve this answer















                    For me i wanted to implement a 2-way handshake, meaning:

                    - the parent window will load faster then the iframe

                    - the iframe should talk to the parent window as soon as its ready

                    - the parent is ready to receive the iframe message and replay



                    this code is used to set white label in the iframe using [CSS custom property]

                    code:
                    iframe



                    $(function() 
                    window.onload = function()
                    // create listener
                    function receiveMessage(e)
                    document.documentElement.style.setProperty('--header_bg', e.data.wl.header_bg);
                    document.documentElement.style.setProperty('--header_text', e.data.wl.header_text);
                    document.documentElement.style.setProperty('--button_bg', e.data.wl.button_bg);
                    //alert(e.data.data.header_bg);

                    window.addEventListener('message', receiveMessage);
                    // call parent
                    parent.postMessage("GetWhiteLabel","*");

                    );


                    parent



                    $(function() 
                    // create listener
                    var eventMethod = window.addEventListener ? "addEventListener" : "attachEvent";
                    var eventer = window[eventMethod];
                    var messageEvent = eventMethod == "attachEvent" ? "onmessage" : "message";
                    eventer(messageEvent, function (e)
                    // replay to child (iframe)
                    document.getElementById('wrapper-iframe').contentWindow.postMessage(

                    event_id: 'white_label_message',
                    wl:
                    header_bg: $('#Header').css('background-color'),
                    header_text: $('#Header .HoverMenu a').css('color'),
                    button_bg: $('#Header .HoverMenu a').css('background-color')

                    ,
                    '*'
                    );
                    , false);
                    );


                    naturally you can limit the origins and the text, this is easy-to-work-with code

                    i found this examlpe to be helpful:
                    [Cross-Domain Messaging With postMessage]







                    share|improve this answer














                    share|improve this answer



                    share|improve this answer








                    edited Dec 13 '17 at 17:40

























                    answered Dec 13 '17 at 17:32









                    Yakir ManorYakir Manor

                    3,85312123




                    3,85312123












                    • i'm dealing with an issue with safari where document in iframe is executing its JS later than parent page which causes the message to be sent earlier than document in iframe is listening to messages; which is exactly opposite from what chrome and firefox do - have you tested your code in safari on ios? btw postMessage with second parameter of value "*" is not quite safe, you should always specify domain

                      – sKopheK
                      Mar 22 '18 at 15:51












                    • Your first block of code, is that on the iframe in the parent or is it on the page that gets loaded into the iframe ?

                      – Demonic218
                      Feb 15 at 9:45

















                    • i'm dealing with an issue with safari where document in iframe is executing its JS later than parent page which causes the message to be sent earlier than document in iframe is listening to messages; which is exactly opposite from what chrome and firefox do - have you tested your code in safari on ios? btw postMessage with second parameter of value "*" is not quite safe, you should always specify domain

                      – sKopheK
                      Mar 22 '18 at 15:51












                    • Your first block of code, is that on the iframe in the parent or is it on the page that gets loaded into the iframe ?

                      – Demonic218
                      Feb 15 at 9:45
















                    i'm dealing with an issue with safari where document in iframe is executing its JS later than parent page which causes the message to be sent earlier than document in iframe is listening to messages; which is exactly opposite from what chrome and firefox do - have you tested your code in safari on ios? btw postMessage with second parameter of value "*" is not quite safe, you should always specify domain

                    – sKopheK
                    Mar 22 '18 at 15:51






                    i'm dealing with an issue with safari where document in iframe is executing its JS later than parent page which causes the message to be sent earlier than document in iframe is listening to messages; which is exactly opposite from what chrome and firefox do - have you tested your code in safari on ios? btw postMessage with second parameter of value "*" is not quite safe, you should always specify domain

                    – sKopheK
                    Mar 22 '18 at 15:51














                    Your first block of code, is that on the iframe in the parent or is it on the page that gets loaded into the iframe ?

                    – Demonic218
                    Feb 15 at 9:45





                    Your first block of code, is that on the iframe in the parent or is it on the page that gets loaded into the iframe ?

                    – Demonic218
                    Feb 15 at 9:45











                    -6














                    • Open the start menu

                    • Type windows+R or open "Run

                    • Execute the following command.

                    chrome.exe --user-data-dir="C://Chrome dev session" --disable-web-security






                    share|improve this answer




















                    • 1





                      Good for quick and dirty test!

                      – user1068352
                      Oct 16 '18 at 22:05











                    • Terrible for anything that is not a quick and dirty test … and already address in the accepted answer.

                      – Quentin
                      Mar 26 at 11:23















                    -6














                    • Open the start menu

                    • Type windows+R or open "Run

                    • Execute the following command.

                    chrome.exe --user-data-dir="C://Chrome dev session" --disable-web-security






                    share|improve this answer




















                    • 1





                      Good for quick and dirty test!

                      – user1068352
                      Oct 16 '18 at 22:05











                    • Terrible for anything that is not a quick and dirty test … and already address in the accepted answer.

                      – Quentin
                      Mar 26 at 11:23













                    -6












                    -6








                    -6







                    • Open the start menu

                    • Type windows+R or open "Run

                    • Execute the following command.

                    chrome.exe --user-data-dir="C://Chrome dev session" --disable-web-security






                    share|improve this answer















                    • Open the start menu

                    • Type windows+R or open "Run

                    • Execute the following command.

                    chrome.exe --user-data-dir="C://Chrome dev session" --disable-web-security







                    share|improve this answer














                    share|improve this answer



                    share|improve this answer








                    edited Mar 20 at 11:13









                    Amsakanna

                    6,77443447




                    6,77443447










                    answered Sep 22 '18 at 6:25









                    sakthi sudhansakthi sudhan

                    835




                    835







                    • 1





                      Good for quick and dirty test!

                      – user1068352
                      Oct 16 '18 at 22:05











                    • Terrible for anything that is not a quick and dirty test … and already address in the accepted answer.

                      – Quentin
                      Mar 26 at 11:23












                    • 1





                      Good for quick and dirty test!

                      – user1068352
                      Oct 16 '18 at 22:05











                    • Terrible for anything that is not a quick and dirty test … and already address in the accepted answer.

                      – Quentin
                      Mar 26 at 11:23







                    1




                    1





                    Good for quick and dirty test!

                    – user1068352
                    Oct 16 '18 at 22:05





                    Good for quick and dirty test!

                    – user1068352
                    Oct 16 '18 at 22:05













                    Terrible for anything that is not a quick and dirty test … and already address in the accepted answer.

                    – Quentin
                    Mar 26 at 11:23





                    Terrible for anything that is not a quick and dirty test … and already address in the accepted answer.

                    – Quentin
                    Mar 26 at 11:23





                    protected by Community Nov 3 '15 at 12:20



                    Thank you for your interest in this question.
                    Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).



                    Would you like to answer one of these unanswered questions instead?



                    Popular posts from this blog

                    Kamusi Yaliyomo Aina za kamusi | Muundo wa kamusi | Faida za kamusi | Dhima ya picha katika kamusi | Marejeo | Tazama pia | Viungo vya nje | UrambazajiKuhusu kamusiGo-SwahiliWiki-KamusiKamusi ya Kiswahili na Kiingerezakuihariri na kuongeza habari

                    Swift 4 - func physicsWorld not invoked on collision? The Next CEO of Stack OverflowHow to call Objective-C code from Swift#ifdef replacement in the Swift language@selector() in Swift?#pragma mark in Swift?Swift for loop: for index, element in array?dispatch_after - GCD in Swift?Swift Beta performance: sorting arraysSplit a String into an array in Swift?The use of Swift 3 @objc inference in Swift 4 mode is deprecated?How to optimize UITableViewCell, because my UITableView lags

                    Access current req object everywhere in Node.js ExpressWhy are global variables considered bad practice? (node.js)Using req & res across functionsHow do I get the path to the current script with Node.js?What is Node.js' Connect, Express and “middleware”?Node.js w/ express error handling in callbackHow to access the GET parameters after “?” in Express?Modify Node.js req object parametersAccess “app” variable inside of ExpressJS/ConnectJS middleware?Node.js Express app - request objectAngular Http Module considered middleware?Session variables in ExpressJSAdd properties to the req object in expressjs with Typescript