How to obtain the dynamic url of the iframe subpage across domains

Sometimes the sub-pages of the iframe will dynamically switch pages. We can only get the information of the sub-pages of the same origin through iframe1.contentWindow.window.location on the parent page. Obtaining cross-domain subpage information will result in an error.

At this time , the cross-domain sub-page information can be obtained through the interface postMessage provided by html5. The following code:

 

The entry test page under the localhost:8000 server: http://localhost:8000/index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h1 id="title"></h1>
<h1 id="title_1"></h1>
</body>
<script>
    window.addEventListener('message',function(rs){
        console.log(rs.data);
        document.querySelector("#title").innerHTML = rs.data;
    });
    var iframe = document.createElement("iframe");
    document.querySelector("body").appendChild(iframe);
    iframe.setAttribute("src","http://localhost:3000/iframe.html");
    //iframe.style.display = "none";

    //Use contentWindow.window to get the sub page address
    /*setTimeout(function () {
        document.querySelector("#title_1").innerHTML = iframe.contentWindow.window.location;
    },1000)*/
</script>
</html>

iframe page under localhost:3000 server: http://localhost:3000/iframe.html

This page will automatically jump to iframe_change.html

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
<h2>This is the content inside the iframe</h2>
</body>
<script>
    window.location.href = "./iframe_change.html";
</script>
</html>

iframe_change page under localhost:3000 server: http://localhost:3000/iframe_change.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h2>iframe already changed</h2>
</body>
<script>
    window.parent.postMessage(window.location.href,"*");
</script>
</html>

Here, postMessage is called to send sub-page information. Use the following code to get the subpage information on the index page.

window.addEventListener('message',function(rs){
        console.log(rs.data);
        document.querySelector("#title").innerHTML = rs.data;
});

 

The above method of obtaining iframe dynamic url across domains can realize a very important problem in WeChat web development:

The main page uses https://open.weixin.qq.com/connect/oauth2/authorize to obtain WeChat user information. The domain name of the main page is limited and needs to be configured on the public platform and is generally configured as an online domain name.

However, in actual local development, the ip of our main page is generally localhost or 192.168.1.198:8080, which will be rejected when obtaining user information on the WeChat browser, causing great inconvenience to development and debugging.

The problem of domain name restrictions can be bypassed by using the above iframe method: the function of obtaining openId is handed over to a separate page

getOpenId.html is responsible for jumping to the WeChat auth page to authorize and obtain the code:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Authorization</title>
    <script>
        function getUrlParam(name){
            var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
            var r = window.location.search.substr(1).match(reg);
            if (r != null) return decodeURIComponent(r[2].replace(/%20/g,"+")); return null;
        }

        var companyAppId = "wx124345678"; //The company's own appid
        var wxCode = getUrlParam('code');
        //If there is no code on the url, jump authorization
        if(!wxCode){
            var url = window.location.href;
            window.location.href = 'https://open.weixin.qq.com/connect/oauth2/authorize?' +
                    'appid='+companyAppId+'&redirect_uri='+encodeURIComponent(url)+
                    '&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect';
        }else {
            //If there is code on the url, it means that the authorization has been completed and the code can be returned to the main page
            window.parent.postMessage(wxCode,"*");
        }
    </script>
</head>
<body>

</body>
</html>

getOpenId.js inserts the iframe into the page for WeChat authorization without affecting the document flow. Once the code is obtained, the iframe is removed.

var wxTool = {
    getOpenId:function (src,callback) {
        var iframe = document.createElement("iframe");
        iframe.style.display = "none";
        document.querySelector("body").appendChild(iframe);
        iframe.setAttribute("src",src);

        window.addEventListener('message',function(rs){
            console.log(rs.data);
            callback(rs.data);
            iframe.remove();
        });
    }
};  

index.html

wxTool.getOpenId("http://live.domain.com/getOpenId.html",function (code) {
        //TODO uses code to request the server to obtain WeChat user information
})

  

Summary: This method may not be the fastest. Write <script> directly under the <head> of the entry page and directly jump to WeChat authorization and then redirect back. It may be the fastest, but once authorized by the network, it may be the fastest. The reason may be that the page will appear briefly blank, which the user does not want to see. The advantage of using iframe is that it is asynchronous and does not affect the loading and running of the main business.

So if you want to quickly present the information of WeChat users on the initial page, use the first method above, otherwise, it may be better to use iframe.

 

 

 

 

  

  

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325157102&siteId=291194637