window.open打开新标签同时修改标签标题

需求
我们在做类似预览的功能时,需要在新窗口打开页面,但页面标题往往需要我们手动定义修改,以下有两种方式可供参考:

方案
1、直接修改title内容

1 const url = 'http://xxx.xxx.xx/abcd'
2 const openObj = window.open(url)
3 const loop = setInterval(() => {
4     if (win.closed) {
5         clearInterval(loop)
6     } else {
7         openObj.document.title = '新标题'
8     }
9 }, 1000)

 

2、使用iframe

 1 const url = 'http://xxx.xxx.xx/abcd'
 2 openNewWindow(url, '新标题')
 3 
 4 function openNewWindow(url, title) {
 5     const win = window.open('about:blank')
 6     win.document.title = title
 7     const iframe = document.createElement('iframe')
 8     iframe.src = url
 9     iframe.style.width = '100%'
10     iframe.style.height = '100vh'
11     iframe.style.margin = '0'
12     iframe.style.padding = '0'
13     iframe.style.overflow = 'hidden'
14     iframe.style.border = 'none'
15     win.document.body.style.margin = '0'
16     win.document.body.appendChild(iframe)
17 }

 

以上两种方式亲测有效,但效果不同,可以依需要选择。
第一种:页面会先加载自带标题,定时执行之后才会变成新的标题,会有闪烁。
第二种:这种方式没有上面的问题,但会插入一个iframe,增加代码结构。

转载自https://blog.csdn.net/qq_39623518/article/details/125765135

posted @ 2023-02-20 17:58  强者之途  阅读(821)  评论(0编辑  收藏  举报
/* 看板娘 */