前端 防止使用 target="_blank" 的惡意攻擊

weixin_33809981發表於2018-04-11

危險的 target=”_blank”

當一個跳轉連結 這麼寫的時候 <a href="./target.html" target="_blank">target _blank</a> 在新開啟的介面,將會暴露一個 opener物件,簡單的理解。這個物件就是父視窗的 windows物件,可以直接使用父視窗的方法, 比如通過window.opener.location = newURL來重寫父頁面的url,即使與父視窗的頁面不同域,跨域的情況下也生效,可以在使用者不知情的情況下,悄悄的改了原有的介面,等使用者在回頭使用時,卻已被釣魚,嚴重的,可以誘導使用者輸入敏感資訊。

解決方案

  1. 使用noopener屬性

通過在a標籤上新增這個noopener屬性,可以將新開啟視窗的opner置為空

<a href="./target.html" target="_blank" rel="noopener">target _blank noopener</a>

  1. window.open並設定opner為空
var otherWindow= window.open();
otherWindow.opener = null;
other = 'http://newurl';
複製程式碼

舊版本瀏覽器

對於舊版本瀏覽器和火狐瀏覽器,可以加上 rel="noreferrer" 更進一步禁用 HTTP 的 Referer 頭

總結

總而言之,如果使用了 target="_blank" 開啟外部頁面,就必須加上 rel="noopener noreferrer" 屬性以保證安全

參考 在新視窗中開啟頁面?小心有坑!

相關文章