Kevin Theys
Kevin Theys

Reputation: 23

How do I replace an iframe source with only javascript?

I have searched for solutions here, but nothing seems to work sadly...

I'm not a developer, but i'm trying to learn more about front-end development.

Currently I configure digital event platforms for events so my knowledge is only html and css for now. The platform I'm working with is an existing platform built by another company and they don't have any answer, except that I could try it with custom code.

The current situation: The platform has exhibition booths and each have a public chat which is just an iframe on a modal. --> There is 1 booth exhibitor that wants the chat to be invisible. So I thought there must be a way to hide that iframe or to change/replace the source with an about:blank.

The second option seems the best, because I want to target that particular chat. And I thought it must be possible to do it with Javascript.

The only thing I can access in the platform is a custom CSS field and a custom Javascript field.

This is the particular iframe, with a generic url (because it was a very long url)

<iframe style="width:100%;height:100%;border: 3px solid var(--colorMain);" src="https://chat.url"></iframe>

I hope someone can help me with this issue.

Upvotes: 2

Views: 413

Answers (2)

Roko C. Buljan
Roko C. Buljan

Reputation: 206121

  • Target your element using attribute selector [] (since you don't have any ID for reference)
  • use IframeElement.src to change the SRC to a desired URI

const EL_iframeTarget = document.querySelector(`[src="https://chat.url"]`);
EL_iframeTarget.src = "https://example.com";
<iframe src="https://chat.url"></iframe>

Upvotes: 4

Adriatic
Adriatic

Reputation: 1287

  1. You give your iFrame an ID like so:
<iframe id="iFrameID" style="width:100%;height:100%;border: 3px solid var(--colorMain);" src="https://chat.url"></iframe>

  1. You get the element using JavaScript and update it's source value:
document.getElementById('iFrameID').src = "some_other_URL";

Upvotes: 1

Related Questions