在 JavaScript 中的同一窗口或标签页中打开 URL

我们将在本文中了解如何在同一窗口或标签页中打开 URL。

在 JavaScript 中使用 window.open() 方法的同一窗口或标签页中打开 URL

window.open() 方法是一种 JavaScript 预定义的窗口技术,用于在浏览器的同一窗口和标签页中打开新标签页或窗口。

根据你的浏览器设置或 window.open() 方法中提供的参数,将打开一个新窗口或标签页。

语法:

window.open(url, "_self");

如果传递此选项,则 URL 将替换先前输出的 _self 值和一个新窗口将出现在同一框架中。

例子:

使用 .html 扩展名保存代码并运行以下脚本。

<html>
   <body>
      <form id="formA" runat="server">
         <div style="text-align:center; font: size 25px;">
            <label>Welcome to same page redirect</label><br><br>
            <input type="button" value="Google.Com" class="btn" id="btnn">
         </div>
      </form>
      <script type="text/javascript">
      document.getElementById("btnn").addEventListener("click", (e) =>{
      let url ="https://www.google.com/";
      window.open(url, "_self");
      })
      </script
   </body>
</html>

输出:

在点击按钮之前:

在 JavaScript 中的同一窗口或标签页中打开 URL

单击该按钮后,它将在同一窗口的同一标签页中打开一个新 URL。

在 JavaScript 中的同一窗口或标签页中打开 URL

在 JavaScript 中使用 location.replace() 方法的同一窗口或标签页中打开 URL

replace() 方法用 JavaScript 中的另一个页面替换当前页面。replace() 方法将当前窗口的 URL 更改为 replace() 方法中指定的 URL。

语法:

location.replace(URL);

此函数仅接受单个 URL 参数。该 URL 链接到必须替换为较早版本的另一个页面。

此方法在同一框架中返回或打开一个带有新页面 URL 的新窗口。

例子:

<!DOCTYPE html>
<html>
   <body>
      <h1>Welcome to same page redirect to different url</h1>
      <h2>The replace Property</h2>
      <button onclick="Function()">Replace document</button>
      <script>
         function Function() {
           location.replace("https://www.google.com")
         }
      </script>
   </body>
</html>

在点击按钮之前:

在 JavaScript 中的同一窗口或标签页中打开 URL

点击按钮后:

在 JavaScript 中的同一窗口或标签页中打开 URL

A