浏览器插件开发相关

2024-05-16  本文已影响0人  湘兰沅芷

1.新建chrome1文件夹,创建manifest.json

{
  "name": "Hello world",
  "description": "show 'hello world'!",
  "version": "1.0",
  "manifest_version": 3,
  "action": {
    "default_popup": "popup.html"
  }
}

action 配置,是chrome1的扩展程序中最重要的配置。如果不添加action,那么chrome1的扩展程序将不能点击,放到插件上无任何反应。

给manifest.json添加 action 配置default_popup,这样点击icon的时候,会打开一个popup页,并显示hello world 创建一个popup.html,内容为:

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>显示出hello world</title>
    <link rel="stylesheet" type="text/css" href="popup.css">
</head>

<body>
    <h1>显示出hello world</h1>
    <button id="clickBtn">点击按钮</button>
    <script src="popup.js"></script>
</body>

</html>

给popup页面设置js脚本、css样式
popup.js

console.log(document.getElementById('clickBtn'));
document.getElementById('clickBtn').addEventListener('click', function () {
  console.log('clicked');
});

popup.css

h1 {
    background-color: antiquewhite;
    font-weight: 100;
}

将 chrome1 安装到谷歌浏览器
安装方式是,直接将chrome1文件夹添加到到谷歌浏览器的扩展程序中,在扩展程序中打开开发者模式,然后加载已解压缩的扩展程序。

点击该插件,会打开一个popup页面,显示hello world,
https://gitee.com/shenshuai89/learn-chrome-extension/tree/master

设置更改content 页面

"content_scripts": [
    {
      "js": [ "content.js"],
      "css":[ "content.css" ],
      "matches": ["<all_urls>"]
    }
  ]

content.js 内容如下:

console.log('content.js hello everybody!');

let newDiv = document.createElement('div');
newDiv.innerHTML = 'hello everybody!';
newDiv.id = 'newDiv';
document.body.appendChild(newDiv);

content.css 内容如下:

#newDiv {
  font-size: 36px;
  color: burlywood;
  position: absolute;
  top: 20px;
  width: 100%;
  text-align: center;
  z-index: 9999;
}

这样就可以动态修改用户打开的页面了。

再使用拓展程序的 API 时,大多数的时候,需要在 manifest.json 文件中声明 permissions 字段。
Chrome 浏览器插件 Manifest.json V3 中权限(Permissions)字段解析:
"permissions":["tabs", "storage", "activeTab", "idle"],
https://blog.csdn.net/guoqiankunmiss/article/details/135597089

消息传递
popup:
chrome.tabs.sendMessage
chrome.runtime.onMessage
content:
chrome.runtime.sendMessage
chrome.runtime.onMessage
background: _ chrome.tabs.sendMessage _ chrome.tabs.onMessage

  "background": {
    "service_worker": "background.js"
  },
// 这是一个在后台执行的文件,多个tab会共享此文件
// 这个文件会随着插件安装执行一次
// 在该文件内存储的数据,会被多tab页面共享
// 在v3版本中,只有js脚本,没有对应的html页面
// 由于此文件在后台执行,为了测试需要,将数据通过消息发送出去
let namespaced = 'BACKGROUND HELLO~~~~';

// 在插件安装完成之后,执行这样一个代码。相当于插件内部就存储了一个颜色。
chrome.runtime.onInstalled.addListener(async () => {
  console.log('background js');
  // 1. Create a new tab
  // chrome.tabs.create(
  //   {
  //     url: chrome.runtime.getURL('newPage.html'),
  //   }
  // );

  // 2. 查询所有tab
  const tabs = await chrome.tabs.query({
    url: [
      'https://blog.csdn.net/*',
      'https://juejin.cn/post/*',
    ],
  });
  // console.log(tabs)
  tabs &&
    tabs.forEach((tab) => {
      // console.log(tab, 'background js tab');
    });

  // 3. 接收到content的消息后,通过 sendResponse将namespaced数据发送出去
  chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
    //  A page requested user data, respond with a copy of `user`
    if (message === 'get-user-data') {
      sendResponse(namespaced);
    }
  });

  // XXX. service worker 通过 chrome.tabs.sendMessage 发送消息,一直未成功 XXX
  /* (async () => {
    // 查询当前tab
    const [tab] = await chrome.tabs.query({
      active: true,
      lastFocusedWindow: true,
    });
    // 和当前tab进行通信
    chrome.tabs.sendMessage(
      tab.id,
      {
        greeting: 'hello',
      },
      function (response) {
        console.log('background 发送消息', response, tab.id);
        // do something with response here, not outside the function
        console.log(response, 'background js: ');
      }
    );
  })(); */

  // 可以设置数据到storage中, 可以将数据设置storage中进行传递
  chrome.storage.sync.set({ namespaced: 'run background js storage' });
});
  "options_ui": {
    "page": "options.html"
  }
上一篇 下一篇

猜你喜欢

热点阅读