需求

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

方案

1、直接修改title内容
const url = 'http://xxx.xxx.xx/abcd'
const openObj = window.open(url)
const loop = setInterval(() => {
	if (win.closed) {
		clearInterval(loop)
	} else {
		openObj.document.title = '新标题'
	}
}, 1000)
2、使用iframe
const url = 'http://xxx.xxx.xx/abcd'
openNewWindow(url, '新标题')

function openNewWindow(url, title) {
	const win = window.open('about:blank')
    win.document.title = title
    const iframe = document.createElement('iframe')
    iframe.src = url
    iframe.style.width = '100%'
    iframe.style.height = '100vh'
    iframe.style.margin = '0'
    iframe.style.padding = '0'
    iframe.style.overflow = 'hidden'
    iframe.style.border = 'none'
    win.document.body.style.margin = '0'
    win.document.body.appendChild(iframe)
}

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

如有其他方式,请评论留言。

Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐