JavaScript 頁面重定向

2021-06-04 12:00 更新

1.3.1【必須】限定跳轉(zhuǎn)目標(biāo)地址

  • 使用白名單,限定重定向地址的協(xié)議前綴(默認(rèn)只允許HTTP、HTTPS)、域名(默認(rèn)只允許公司根域),或指定為固定值;

  • 適用場景包括,使用函數(shù)方法:location.hrefwindow.open()、location.assign()、location.replace();賦值或更新HTML屬性:a.href、ifame.srcform.actionembed.src、object.data、link.hrefarea.href、input.formaction、button.formaction;

// bad: 跳轉(zhuǎn)至外部可控的不可信地址
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);
以上內(nèi)容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號(hào)
微信公眾號(hào)

編程獅公眾號(hào)