乐闻世界logo
搜索文章和话题

How to redirect page inside iframe to another one but we must stay in iframe

1个答案

1

To redirect a page within an iframe to another page while keeping it displayed inside the iframe, several methods can be used. Here are two common approaches:

Method 1: Using JavaScript to Change the iframe's src Attribute

You can use JavaScript to change the iframe's src attribute and load a new page. This method is straightforward and easy to implement. For example, suppose your iframe element has an ID of myIframe, and you want to change its content to the page at https://example.com.

html
<iframe id="myIframe" src="https://current-website.com"></iframe> <script> function changeIframeUrl() { var iframe = document.getElementById('myIframe'); iframe.src = "https://example.com"; } </script>

Method 2: Redirecting Within the iframe's Page Using HTML or JavaScript

If you can access the code of the page inside the iframe, you can directly redirect it using HTML meta tags or JavaScript within the page.

Using HTML meta tag:

Add the following code in the <head> section of the iframe's page:

html
<meta http-equiv="refresh" content="0;url=https://example.com">

This line of code will redirect the page immediately upon loading to https://example.com.

Using JavaScript:

Add the following code in a <script> tag within the iframe's page:

javascript
window.location.href = "https://example.com";

This code will cause the page inside the iframe to redirect to the new URL.

Summary

Both methods can redirect the page without leaving the iframe. The choice of method depends on whether you can control the content of the iframe's page. If you can control it, you can use redirection code directly within the internal page; if not, you need to change the iframe's src attribute to achieve redirection.

2024年8月13日 10:33 回复

你的答案