Dynamically change the src of an iframe

Asked

Viewed 2,375 times

-3

I can change the src an iframe for any value? This is possible?

document.getElementById('idIframe').src = "www.google.com"
  • Chance url? src is img and href is Location. document.querySelector('img#idIframe').src = "https://www.google.com/images/branding/googlelogo/1x/googlelogo_color_150x54dp.png"

  • 1

    Of course you can. You tried?

  • Yes... it’s normal for that to happen

  • Why make changes dynamically? What’s the advantage of doing this? Putting src directly in iframe won’t save code?

1 answer

1

How you’re doing is right. You have to consider two things:

  • some urls do not open within iframes by cors protection, which thus prevents you from manipulating the page inside an iframe
  • the src has to be a valid url. Either you put a relative url (as in the example I gave) or you put a full address with http://

Example: https://jsfiddle.net/2a37sbrp/

Browser other questions tagged

You are not signed in. Login or sign up in order to post.