0

I have the following iframe in my code.

<iframe src="http://www.w3schools.com" id="myframe" name="myframe" height="100%" width="100%"></iframe>

I need to get the new URL of the page which is displayed after some navigations within the iframe.

I tried several methods but none of them delivered what I wanted. Some methods returned the same URL given as src. Others resulted in security issues.

How can I get this done using AngularJS?

(Asking for a friend)

Dishon
  • 107
  • 2
  • 9

2 Answers2

2

As you commented on my last answer, here is my new one form Marco Bonelli

Same Origin security Policy

You can't access an <iframe> with javascript, it would be a huge security flaw if you could do it. For the Same Origin Security Policy, any browser blocks any script trying to access a frame that has another origin.

For example if you are in http://www.example.com and want to acces an with src="http://www.anothersite.com" you'll not be able to do that, because the frame has another origin.

Origin is considered different if at least one of the following variables 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.

Workaround

Even thought Same Origin Policy blocks scripts from manipulating content of sites with a different origin, if you own both domains/sites, you can work around this problem using window.postMessage and its relative event window.onmessage 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;
    }
});
Community
  • 1
  • 1
Luca
  • 1,678
  • 3
  • 27
  • 36
-1

Would be the solution without angularJS. It's just pure js.

document.getElementById("myframe").contentWindow.location.href
Luca
  • 1,678
  • 3
  • 27
  • 36
  • The above code returns the following error. Blocked a frame with origin "http://127.0.0.1:50129" from accessing a cross-origin frame. – Dishon Aug 03 '15 at 15:37