法一:<a/>
// target="_blank"表示保留当前页面,用新标签页打开
<a href="https://smallpdf.cn" target="_blank" rel="noreferrer">收集优质网站资源</a>
法二:window.location.href
window.location.href="https://smallpdf.cn";
法三:window.open()
// "_blank" 表示保留当前页面,用新标签页打开
window.open("https://smallpdf.cn", "_blank");
<a>
警告信息
问题描述
<a href="https://smallpdf.cn" target="_blank"/>
# 上面的写法,会出现下面的警告信息:
warning Using target="_blank" without rel="noreferrer" is a security risk: see
https://html.spec.whatwg.org/multipage/links.html#link-type-noopener react/jsx-no-target-blank
解决方案
# 增加属性:rel="noreferrer"
<a href="https://smallpdf.cn" target="_blank" rel="noreferrer"/>
原因详解
当使用target="_blank"
打开新标签页时,新页面的window.opener
是指向前一个页面,这样就可以控制前一个页面。譬如:当新旧页面在同一个域名下时,在新页面控制台输入 window.opener.alert(1)
,会发现旧页面弹出消息1
。当新旧页面不在同一个域名时,通过window.opener.location.replace
可以改变旧页面的url。所以还是加上rel="noreferrer"
,把opener
对象设置为null
,以防后患。
相关链接
页面跳转传递参数
# 传参页面
let a = {
key:'value'
}
// 对参数进行序列化
let astr = JSOS.stringfy(a);
let url = 'https://learn-anything.cn/search?input='+astr;
window.open(url);
# 接受参数页面:https://learn-anything.cn/search
// window.location,存储了本页面相关所有数据
let query = window.location.query;
# 参数解析方式:
const urlTemp = require('url');
let parsedUrl = urlTemp.parse(window.location.href, true);
let para = parsedUrl.query.astr;
# 反序列化得到参数,如果是非序列化参数,无需此步直接使用参数
let a = JSON.parse(para);