百度去广告chrome插件

插件的安装不多提了,自行百度

插件目录结构

manifest.json

{
  "manifest_version": 2,
  "name": "百度清理",
  "version": "1.0.0",
  "description": "百度去广告",
  "icons":{
    "16": "icon.jpg"
  },
  "content_scripts": [
    {
      "matches": [
        "https://www.baidu.com/*"
      ],
      "js": ["content-script.js"]
    }
  ]
}

content-script.js

由于百度网页里自带jquery,所以不需要另外引入jquery

(function () {
   let calFun = function(){
        function clearGap() {
            $('#content_left>div').each(function(){
                let div = $(this)
                div.find('.c-gap-left').each(function(){
                    if($(this).text().indexOf('广告') > -1) {
                        div.remove();
                        return false;
                    }
                })
            })
            console.log('广告清理完毕')
        }

        $.ajaxSetup({
            complete: function(xhr){
                clearGap()
                setTimeout(clearGap,2000)
            }
        })

        clearGap()
        setTimeout(clearGap,2000)
    }

    injectScript(calFun)

    // 页面插入js
    function injectScript(calFun) {
        const script = document.createElement('script');
        script.textContent = `(${calFun})();`;
        document.documentElement.appendChild(script);
    }
})();

icon.jpg

image

代码介绍

clearGap()

  • 方法中的逻辑是删除广告所在的dom
  • 由于广告的生成是有延迟的,所以需要再延迟执行一次清除

injectScript()

  • 方法中的逻辑是将删除逻辑代码注入到百度的页面中

$.ajaxSetup complete

  • 方法是让百度页面发送ajax请求后再执行一次clearGap()
  • 这是因为百度搜索的翻页是通过ajax请求渲染的
不积跬步无以至千里
原文地址:https://www.cnblogs.com/xiaogblog/p/15480770.html