Cross domain iframe issue

前端 未结 5 1719
[愿得一人]
[愿得一人] 2020-11-21 06:14

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

5条回答
  •  我在风中等你
    2020-11-21 07:06

    It can happen only if you have control for both sites

    you can use postMessage

    here's how you can apply it

    first, you can add the below code to the site you want to retrieve data from

     
        

    the second step you can add this code below to the other domain you want to send a message or the data to it

     window.addEventListener("message", function (message) {
            if (message.origin == "http://firstdomain.com") {
                console.log(message)
            }
        });

    and please note you must add the test() function on the onload attribute of the iframe cause if the function runs before the iframe was loaded it will become useless and it won't send data

提交回复
热议问题