JS打开新窗口(window.open() 、href)
生活随笔
收集整理的這篇文章主要介紹了
JS打开新窗口(window.open() 、href)
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
JS打開新窗口
常用于文件、圖片預(yù)覽,或者加載一個(gè)新頁面。
window.open() - 打開新窗口
用法:
window.open(strUrl, strWindowName, [strWindowFeatures]);- strUrl: 新窗口需要載入的url地址,項(xiàng)目中我們打開的是一個(gè)在線文檔。
- strWindowName:新窗口的名字,通過這個(gè)名字我們可以獲得新窗口的引用,容易重復(fù),如果我們希望每次打開新窗口都是一個(gè)全新的窗口,可以設(shè)置成關(guān)鍵字 “_blank”。
- strWindowFeatures:新窗口的一些設(shè)置,比如是否顯示菜單欄,是否可以滾動(dòng)和縮放窗口大小等。
示例:
window.open("https://www.baidu.com", "_blank", "resizable,scrollbars,status");window.location - 更新當(dāng)前窗口
加載給定URL的內(nèi)容資源到這個(gè)Location對(duì)象所關(guān)聯(lián)的對(duì)象上。
屬性:
window.location.href = strUrl; //方法:
window.location.assign(strUrl); window.location.replace(strUrl); // 不會(huì)保存到瀏覽器會(huì)話的歷史 Historya 標(biāo)簽 href 屬性
<a href="strUrl" target="_blank">點(diǎn)擊打開新窗口預(yù)覽</a>動(dòng)態(tài) a 標(biāo)簽
<div onclick="openNewWindow()">點(diǎn)擊打開新窗口預(yù)覽</div> function openNewWindow() {const strUrl = "https://www.baidu.com";let a = document.createElement("a");document.body.appendChild(a);a.style = "display: none";a.target = "_blank";a.href = strUrl;a.click();document.body.removeChild(a); }iOS window.open 無效
可以采用 window.location 和 a 標(biāo)簽 的方式解決。
或者調(diào)整腳本時(shí)序,先創(chuàng)建一個(gè)空窗口,再加載內(nèi)容,而不是 window.open(strUrl) 同時(shí)完成。
var windowReference = window.open();myService.getUrl().then(function(url) {windowReference.location = url; });安全問題
打開新窗口,可以通過 window.opener 獲取原窗口的引用,利用這個(gè)引用,可以修改原窗口的屬性,比如 url,所以解決安全問題就需要把這個(gè)引用切斷。
window.open 的方式,如下處理
const newWindow = window.open("https://www.baidu.com"); newWindow.opener = null;a 標(biāo)簽 的方式需要添加 rel 屬性:
<a href="strUrl" target="_blank" rel="noopener noreferrer">點(diǎn)擊打開新窗口預(yù)覽 </a>性能問題
除了安全隱患外,還有可能造成性能問題。通過target="_blank"打開的新窗口,跟原來的頁面窗口共用一個(gè)進(jìn)程。如果這個(gè)新頁面執(zhí)行了一大堆性能不好的 JavaScript 代碼,占用了大量系統(tǒng)資源,那你原來的頁面也會(huì)受到池魚之殃。
.END
總結(jié)
以上是生活随笔為你收集整理的JS打开新窗口(window.open() 、href)的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 在unity 中,使用http请求,下载
- 下一篇: Chapter7:非线性控制系统分析