防止運(yùn)營商劫持揩瞪,前端解決辦法
[toc]
常見的劫持方式:
按照劫持的方法不同,我將劫持分為下面兩類:
- 跳轉(zhuǎn)型劫持:用戶輸入地址A盗棵,但是跳轉(zhuǎn)到地址B
- 注入型劫持:有別于跳轉(zhuǎn)型型劫持壮韭,指通過在正常的網(wǎng)頁中注入廣告代碼(js北发、iframe等),實(shí)現(xiàn)頁面彈窗提醒或者底部廣告等喷屋,又分為下面三個(gè)小類:
- 注入js類劫持:在正常頁面注入劫持的js代碼實(shí)現(xiàn)的劫持
- iframe類劫持:將正常頁面嵌入iframe或者頁面增加iframe頁面
- 篡改頁面類劫持:正常頁面出現(xiàn)多余的劫持網(wǎng)頁標(biāo)簽琳拨,導(dǎo)致頁面整體大小發(fā)生變化
解決辦法:
針對注入js,添加資源過濾
/**
* <div class="page" data-res="trust"></div>
* <link rel="stylesheet" href="css/reset.css" data-res="trust">
* 為css屯曹,js狱庇,div,添加H5自定義標(biāo)簽恶耽,data-res="trust",然后遍歷dom密任,將不是自定義標(biāo)簽dom資源清除掉。
*/
//原生版
function clearAdv() {
var head = document.getElementsByTagName('head')[0];
var children = head.childNodes;
var res;
var source = 'trust'; //信任資源
for (var i in children) {
if (children.hasOwnProperty(i)) {
tagName = children[i].tagName;
if (tagName && tagName == 'SCRIPT') {
res = children[i].dataset['res'];
if (res != source) {
head.removeChild(children[i]);
}
}
}
}
var body = document.getElementsByTagName('body')[0];
if (body) {
children = body.childNodes;
for (var k in children) {
if (children.hasOwnProperty(k)) {
var tagName = children[k].tagName;
if (tagName) {
res = children[k].dataset['res'];
if (res != source) {
body.removeChild(children[k]);
}
}
}
}
}
}
//zepto版
function clearAdv() {
var $body = $('body');
var source = 'trust'; //信任資源
var $head = $('head');
var $headScript = $head.children('script');
$headScript.each(function () {
if ($(this).data('res') != source) {
$(this).remove();
}
});
var $bodyScript = $body.children('script');
$bodyScript.each(function () {
if ($(this).data('res') != source) {
$(this).remove();
}
});
var $div = $body.children();
$div.each(function () {
if ($(this).data('res') != source) {
$(this).remove();
}
});
}
針對加載資源偷俭,添加白名單控制
csp(Content Security Policy)內(nèi)容安全策略浪讳,屬于瀏覽器的的一種安全策略,以白名單作為信任機(jī)制涌萤,來限制網(wǎng)站是否可以包涵某網(wǎng)站來源淹遵。
詳細(xì)配置說明
https://imququ.com/post/content-security-policy-reference.html
把以下代碼,放到頁面head里负溪。
<meta http-equiv="Content-Security-Policy"
content="default-src *; frame-src 'self' style-src 'self' http://*.trust.com https://*.trust.com 'unsafe-inline'; script-src 'self' 'unsafe-inline' 'unsafe-eval' http://*.trust.com https://*.trust.com;">
針對iframe嵌套
把以下代碼透揣,放到頁面head里。
(function (window) {
if (window.location !== window.top.location) {
window.top.location = window.location;
}
})(this);
判斷當(dāng)前的窗口有沒有被嵌套在別的窗口中川抡,如果window.top = window.self 沒嵌套 辐真,當(dāng)前窗口就是頂層窗口