当前位置:网站首页 > 办公教程 > 正文

chrome插件-入门

访客 发布于2023-10-06 办公教程 102

chrome插件的作用

1、屏蔽网页上的广告,提高浏览速度和减少视觉干扰
2、捕捉和编辑网页截图
3、改善在社交媒体平台上的体验,例如提供额外的功能,或自定义外观和布局
4、网页翻译
5、保存和组织网页书签和笔记
6、管理日程安排,设置提醒和定时器

去广告的实战案例

在这里插入图片描述
开发之前最关键的是了解下图框架,background.js、content.js、popup.js等
在这里插入图片描述

background.js

可以处理安装提示

chrome.runtime.onInstalled.addListener(function() {
  console.log("隐藏广告插件V2,已安装");
});

可以接收消息

chrome.runtime.onMessage.addListener(function(message, sender, sendResponse) {
  console.log("onMessage ", message);
  chrome.tabs.query({
    active: true,
    currentWindow: true
  }, function(tabs) {
    const activeTab = tabs[0];
    setTimeout(()=>{
      chrome.tabs.sendMessage(activeTab.id, message);
    },2000)
  });
});

content.js

隐藏广告的方法,不用管popup.js和background.js直接在content.js写入以下内容


setTimeout(() => {
  $("#aswift_1").hide()
  $(".programmer1Box").hide()
}, 1500)

popup.js

它是popup.html配套的脚本,可以实现点击发送消息


document.getElementById('buttonId').addEventListener('click', function () {
  let message = document.getElementById('name').value
  chrome.runtime.sendMessage({ action: 'hideAds',data: message });
});
popup.html

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Patrick的进阶笔记</title>
    <link rel="stylesheet" type="text/css" href="../css/popup.css" />
  </head>
  <body>
    <input type="text" id="name">
    <button id="buttonId">隐藏广告</button>
    <script src="../js/jquery-3.6.0.min.js"></script>
    <script src="../js/popup.js"></script>
  </body>
</html>

在这里插入图片描述





Copyright 571400.cn.Some Rights Reserved.琼ICP备20000547号