0

My website provides functionality for embedding a video from my website via an iframe (similar to Youtube or any other video portals).

However, is there a way to exactly detect, which website included mine as an iframe.

Tried within my iframe embed, trying to detect parent's URL

if (window !== window.top) {
     console.log(window.top.location.href);
     console.log(window.parent.location.href);
}

but ended up with an error

Uncaught DOMException: Blocked a frame with origin "https://myurl.com" from accessing a cross-origin frame.
    at console.log (<anonymous>)
    at https://www.myurl.com/embed/1544401:20:21

Is there a workaround?

UPD. Solved by using document.referrer

Denis
  • 322
  • 1
  • 4
  • 15

1 Answers1

0

You can't access an <iframe> with different origin using JavaScript, it would be a huge security flaw if you could do it. For the same-origin policy browsers block scripts trying to access a frame with a different origin.

you can work around this problem using window.postMessage and its relative message event to send messages between the two pages, like this:

//in your main page 
const frame = document.getElementById('your-frame-id');
frame.contentWindow.postMessage(/*any variable or object here*/, 'http://your-second-site.com');



//In your <iframe> (contained in the main page):
window.addEventListener('message', event => {
    // IMPORTANT: check the origin of the data! 
    if (event.origin.startsWith('http://your-first-site.com')) { 
        // The data was sent from your site.
        // Data sent with postMessage is stored in event.data:
        console.log(event.data); 
    } else {
        // The data was NOT sent from your site! 
        // Be careful! Do not use it. This else branch is
        // here just for clarity, you usually shouldn't need it.
        return; 
    } 
});

This method can be applied in both directions, creating a listener in the main page too, and receiving responses from the frame. The same logic can also be implemented in pop-ups and basically any new window generated by the main page (e.g. using window.open()) as well, without any difference.

or just disable the same origin policy in your browser

  • The problem is that main page does not belong to me and I want to detect its url within my iframe (the website that belongs to me). Youtube does it somehow... – Denis May 29 '21 at 21:48
  • Plagiarized from https://stackoverflow.com/a/25098153/874188 – tripleee Dec 13 '21 at 04:47