阅读(3935) (0)

JavaScript 页面重定向

2021-05-31 16:39:24 更新

1.3.1【必须】限定跳转目标地址

  • 使用白名单,限定重定向地址的协议前缀(默认只允许HTTP、HTTPS)、域名(默认只允许公司根域),或指定为固定值;

  • 适用场景包括,使用函数方法:location.hrefwindow.open()location.assign()location.replace();赋值或更新HTML属性:a.hrefifame.srcform.actionembed.srcobject.datalink.hrefarea.hrefinput.formactionbutton.formaction

// bad: 跳转至外部可控的不可信地址
const sTargetUrl = getURLParam("target");
location.replace(sTargetUrl);


// good: 白名单限定重定向地址
function validURL(sUrl) {
    return !!((/^(https?:\/\/)?[\w\-.]+\.(qq|tencent)\.com($|\/|\\)/i).test(sUrl) || (/^[\w][\w/.\-_%]+$/i).test(sUrl) || (/^[/\\][^/\\]/i).test(sUrl));
}


const sTargetUrl = getURLParam("target");
if (validURL(sTargetUrl)) {
    location.replace(sTargetUrl);
}


// good: 制定重定向地址为固定值
const sTargetUrl = "http://www.qq.com";
location.replace(sTargetUrl);