remove_baidu_ad

去除百度搜索结果中的广告

Από την 09/04/2020. Δείτε την τελευταία έκδοση.

// ==UserScript==
// @name         remove_baidu_ad
// @namespace    http://tampermonkey.net/
// @version      0.6
// @description  去除百度搜索结果中的广告
// @author       ipuppet
// @match        https://www.baidu.com/s?*
// @match        https://www.baidu.com/
// @match        https://zhidao.baidu.com/search?*
// @grant        none
// ==/UserScript==
var adCount = 0;
(function () {
    'use strict';

    function display() {
        let right = $('#content_right');
        try {
            if (right.html().charAt(0) !== '已') {
                right.html('已过滤 ' + adCount + ' 条广告。');
                console.log('display')
            }
        } catch (e) {
            console.log(e)
        }
    }

    //获取广告元素
    function getAdElements() {
        let ads = [];
        //左侧
        $('#content_left>div').each((i, e) => {
            let spanList = $(e).find('span');
            for (let span of Object.values(spanList)) {
                if ($(span).text() === '广告') {
                    ads.push($(e));
                    break;
                }
            }
        });
        //shadow
        ads.push($('::shadow div'));
        return ads
    }

    //清除广告
    function clearAd() {
        let ads = getAdElements();
        if (ads.length > 0) {
            if (ads[0].selector !== '::shadow div' && ads[0].length > 0) {
                for (let item of ads) {
                    item.remove();
                    adCount++
                }
            }
        }
        display();
        setTimeout(() => {
            clearAd()
        }, 50)
    }

    if (window.location.host === 'zhidao.baidu.com') {
        if (document.getElementsByClassName('bannerdown').length > 0)
            document.getElementsByClassName('bannerdown')[0].remove();
        document.getElementsByTagName('aside')[0].remove()
    } else if (window.location.host === 'www.baidu.com') {
        // 监听url变化
        if (("onhashchange" in window) && ((typeof document.documentMode === "undefined") || document.documentMode === 8)) {
            // 浏览器支持onhashchange事件
            window.onhashchange = hashChanged;
        } else {
            // 不支持则用定时器检测的办法
            setInterval(function () {
                if (isSearchResultPage()) {
                    hashChanged();
                }
            }, 150);
        }

        function hashChanged() {
            if (isSearchResultPage()) {
                clearAd()
            }
        }

        function isSearchResultPage() {
            let s = window.location.search;
            return s !== '';
        }

        if (isSearchResultPage()) {
            clearAd()
        }
    }
})();