Search code examples
htmliframegoogle-sites

Create a dynamic iframe that receive its URL from the address bar


I have a simple website, and I'd like to hide some URL addresses using iframe.

Is there any way to create a code that receive the ifram's URL from the address? Something like that: www.myschool.com/iframe?url=www.stackoverflow.com

I'm looking for a code that enables to automatically receive the iframe's URL (www.stackoverflow.com) from the address bar, to be embedded in my website.

Thanks!


Solution

  • You can use the split method on the string of the url and take everything after the '?' by targetting the [1] position of the resulting array, then change the iframe's 'src' attribute to that url.

    var url = window.location.href.split('?')[1];
    document.querySelector('iframe').setAttribute('src',url);

    Try breaking the first line into two like this:

    var url = window.location.href;
    url.split('?')[1];
    document.querySelector('iframe').setAttribute('src',url);