近期公司站点通过联通4G网站访问时被运营商插入广告代码,通过手机抓包定位到运营商值入的广告代码。植入的广告代码通过在固定url的请求中添加内容插行一段js,通过body.appendChild在页面引入一段js代码。想到一个应急方案,通过改写appendChild来拦截广告,经测试有效。代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
(function() {
var rootEl = top.document.body;
var originAppendChild = rootEl.appendChild;
try {
rootEl.appendChild = function (elem) {
var src = '';
if (typeof elem == 'object' && elem != null && elem.getAttribute) {
src = elem.getAttribute('src');
}
if (typeof src == 'string' && src.length) {
if ( src.match(/^(?:http(?:s)?:)?\/\/\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}/)
|| src.match(/cifenqi\.com/) != null) {
return;
}
}
originAppendChild.apply(rootEl, [].slice.call(arguments, 0));
}
}
catch(e) { }
})();

ISP广告干的是非法勾当多使用ip地址,因此直接屏蔽ip地址的元素。此方法只能应急可被绕过,难怪某度、某宝纷纷启用全站https。