Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get current page loaded url from iframe [duplicate]

I'm using iframe to load faroo.com as default src in frame when i search and move to other webpage using faroo.But still in the iframe src its display faroo.com only i wanted to capture url of page that has loaded in iframe

<!DOCTYPE html>
<html>
<head>
    <script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.11.1.min.js"></script>
    <script type="text/javascript">
    $(function(){
        $('#frameid').load(function(){
            var z=$('#frameid').attr('src');
            console.log('hi '+z);
        });

        $('#clicked').on('click', function(){
            $('#frameid').attr('src', 'http://www.faroo.com/');    
        });
    });

</script>

</head>
<body>

<iframe width="100%" height="500px" id="frameid" src="" name="iframe_a" ></iframe>

<p><input type="button" value="click me!" id="clicked"></p>

</body>
</html>

The o/p at console.log is always faroo.com not the current website that has loaded

like image 677
user4082518 Avatar asked Sep 26 '14 08:09

user4082518


People also ask

How do I find the current URL of an iframe?

To get current URL from an iframe with JavaScript, we can use the contentWindow. location. href property. Then we get the current URL of the iframe with the contentWindow.

How can I check if an iframe URL is loaded?

setTimeout(function(){ if (//something shows iframe is loaded or has content) { //my code } else { $('#myIframe'). attr("src",""); //stop loading content } },5000);

How do you get a current URL from a page?

If you're using JavaScript in the browser you can get the full current URL by using window. location. href .

What is an iframe URL?

An iFrame, also knowns as Inline Frame, is an element that loads another HTML element inside of a web page. They are commonly used to embed specific content like external ads, videos, tags, or other interactive elements into the page.


1 Answers

Seem likes there is a hack to make this work and I actually can't believe it's even allowed. This is how it seems to work:

1) Change the domain to match iframe:

document.domain = <iframe_domain>

2) Get the URL like so:

console.log($('iframe')[0].contentWindow.location.href)

In my opinion, this should not have worked, but it does. I tested with the following in Safari, Chrome and Firefox all latest version as of 02/01/2017:

Main: http://subdomain.website.com iframe: http://www.website.com

What do you think? Is this permanently allowed or is it an oversight that will be patched soon?

Update

I started another thread for discussion here regarding browser security.

Isn't This A Serious Browser Security Issue? RE: Cross-Domain iframe Hack

Update 2

Seems like this will always be supported for specific cases.

https://developer.mozilla.org/en-US/docs/Web/Security/Same-origin_policy

like image 89
juminoz Avatar answered Sep 21 '22 14:09

juminoz