0

I hope I'll find a solution to my problem here. Suppose it is a code:

<iframe src="https://anyweb.ext/anymouse"></iframe>

As the page loads, it gets redirected to a new window. I want it not to be redirected, but the redirected URL should be replaced with iframe src="". I want to do it JavaScript.

Sercan
  • 4,739
  • 3
  • 17
  • 36

1 Answers1

0
Method-1

If you assign data-src to the src attribute of the <iframe> element using Javascript, the <iframe> will open on the same page.

const mainPageButton = document.getElementById('mainPageButton');
const talkPageButton = document.getElementById('talkPageButton');
const iframeElement = document.getElementById('specialIFrame');
const mainPage = "https://en.wikipedia.org/";

/* Opens the "data-src" attribute of the <iframe> element. */
mainPageButton.addEventListener('click', function(){
  iframeElement.setAttribute("src", mainPage)
});

/* Opens the address defined in the mainPage variable. */
talkPageButton.addEventListener('click', function(){
  iframeElement.setAttribute("src", iframeElement.dataset.src)
});
button { margin-bottom: 10px; margin-left: 75px; }
<button id="mainPageButton">OPEN Main Page</button>
<button id="talkPageButton">Open Talk Page</button><br>

<iframe id="specialIFrame" data-src="https://en.wikipedia.org/wiki/Talk:Main_Page" src="about:blank" width="500"></iframe>
Method-2

Adding the target attribute to the <a> element and the name attribute to the <iframe> element opens the website within the same page.

a{ display: block; }
<a target="myIframe" href="https://en.wikipedia.org/wiki/Main_Page">Open</a> 

<iframe name="myIframe"></iframe>
References
Sercan
  • 4,739
  • 3
  • 17
  • 36
  • You are telling us how we can change the source of 'iframe', But the main part of my question is how did we stop the redirect and get the URL that is going to be redirected. – Farooq Chohan Jan 17 '22 at 09:56
  • If the redirecting is ` – Sercan Jan 17 '22 at 10:00
  • I tried both of your methods, but when I clicked the button it was redirected to a new page in the same window. This URL **_https: //anyweb.ext/anymouse _** is a short URL. But when it is redirected, the URL is changed to the full URL. – Farooq Chohan Jan 17 '22 at 10:14