Get current URL from IFRAME

前端 未结 7 1398
小鲜肉
小鲜肉 2020-11-22 08:08

Is there a simple way to get the current URL from an iframe?

The viewer would going through multiple sites. I\'m guessing I would be using something in javascript.<

7条回答
  •  栀梦
    栀梦 (楼主)
    2020-11-22 08:52

    Some additional information for anyone who might be struggling with this:

    You'll be getting null values if you're trying to get URL from iframe before it's loaded. I solved this problem by creating the whole iframe in javascript and getting the values I needed with the onLoad function:

    var iframe = document.createElement('iframe');
    iframe.onload = function() {
    
        //some custom settings
        this.width=screen.width;this.height=screen.height; this.passing=0; this.frameBorder="0";
    
        var href = iframe.contentWindow.location.href;
        var origin = iframe.contentWindow.location.origin;
        var url = iframe.contentWindow.location.url;
        var path = iframe.contentWindow.location.pathname;
    
        console.log("href: ", href)
        console.log("origin: ", origin)
        console.log("path: ", path)
        console.log("url: ", url)
    };
    
    iframe.src = 'http://localhost/folder/index.html';
    
    document.body.appendChild(iframe);
    

    Because of the same-origin policy, I had problems when accessing "cross origin" frames - I solved that by running a webserver locally instead of running all the files directly from my disk. In order for all of this to work, you need to be accessing the iframe with the same protocol, hostname and port as the origin. Not sure which of these was/were missing when running all files from my disk.

    Also, more on location objects: https://www.w3schools.com/JSREF/obj_location.asp

提交回复
热议问题