开发Chrome插件获取当前页面Cookie

前言

看《重来》的时候有提到,把自己的需求做成产品,给更多人提供价值。
就是本篇的文章的由来。

我的需求场景,因为要用postman测公司开发的接口,公司接口通过cookie做鉴权,
所以我每次都要f12,然后从Network面板手工复制出来,对于技术来讲,一定要注意一个事情手工做三遍以上的时候,要思考去提效。三次以上的代码重构方法,三次以上的手工操作脚本自动化,所以我就想做一个Chrome插件,来获取当前的页面Cookie。
我希望这一篇文章不仅仅是一个照着copy的教程,这里一步步从构思到实现以及完善的过程展现。

首先看一遍官网教程,不要看别人的二手资料,包括我的,能直接吃官网的一手资料的现在关掉文章即可。如果理解还有一点困难,那就顺着往下看。

资料

官网开发文档如下
https://developer.chrome.com/docs/extensions?hl=zh-cn
Hello World示例如下
https://developer.chrome.com/docs/extensions/get-started/tutorial/hello-world?hl=zh-cn

效果是单机插件按钮,弹出一个端面
Pasted image 20231230210748

分析HelloWorld示例

四个文件,分别是一个html,一个json,一个js,和一个png格式的图片

看来插件开发不需要很多的技术储备,会js就够了,很开心不需要补课了。不过哪怕你不会也没关系,有其他语言的底子,js读懂还是不困难的。

文件内容不多。这里直接全部贴出来、

manifest.json

此 JSON 文件描述了扩展程序的功能和配置。也是插件最关键的文件,目录结构更为复杂的小程序,此文件必须位于根目录下。类似于安卓的注册文件,小程序的注册表之类的职能。

{
   
  "name": "Hello Extensions",// 插件名
  "description": "Base Level Extension", //说明
  "version": "1.0",// 插件的版本
  "manifest_version": 3, // chrome扩展文件的发行版本,类似vue2 还是vue3的声明
  "action": {
   
  // 声明 Chrome 应用作扩展程序的操作图标的图片,以及当用户点击扩展程序的操作图标时在弹出式窗口中显示的 HTML 页面。
    "default_popup": "hello.html",
    "default_icon": "hello_extensions.png"
  }
}

hello.html

插件的端面,前面介绍中有截图

<html>
  <body>
    <h1>Hello Extensions</h1>
    <script src="popup.js"></script>
  </body>
</html>

可以看到,这里就是端面展示的Hello Extensions这句话,然后引入了一个js文件。

  • 注意不可以直接用script标签写,会报错。

popup.js

console.log('This is a popup!');

打印一行日志,是这个效果。

从本地加载扩展程序

Pasted image 20231230213318

可以看到已经加载成功了,图标正是最后一个图片文件hello_extensions.png
Pasted image 20231230213426

单机Hi图标,在Pasted image 20231230210748
右键选检查,会再跳出来一个窗口,这个窗口用于调试插件。
Pasted image 20231230213909

从本例子基本可以了解到一个插件的执行流程,
manifest注册插件的信息,然后链接到端面,端面引入了js用于逻辑控制。

开发设计

万事谋而后动,想清楚再写代码就是填空题。
已经明白示例的逻辑了,接下来思考如何实现我期望的功能。
1.获取页面的cookie
2.先打印cookie到端面(控制台要每次审查再进去看,没端面那么方便)
3.把打印内容复制进剪切板
4.确认能够复制以后,整理cookie的格式,使cookie文本可以直接复制进postman使用。

获取页面的cookie

首先看api文档
https://developer.chrome.com/docs/extensions/reference/api/cookies?hl=zh-cn

1.先给注册操做cookie的权限 manifest

{
   
  "name": "Hello Extensions",
  "description": "Base Level Extension", 
  "version": "1.0",
  "manifest_version": 3, 
    // 新增如下
  "permissions": [
    "cookies"
  ],
  "host_permissions": [
    "http://*/*",
    "https://*/*"
  ],
  "action": {
   
    "default_popup": "hello.html",
    "default_icon": "hello_extensions.png"
  }
}

2.尝试把cookie带到端面 hello.html

<html>
  <body>
    <h1>Get Page Cookies</h1>
    <input type="text" id="url" placeholder="Enter URL">
    <button id="get-cookies">Get Cookies</button>
    <div id="cookie-list"></div>
    <script src="popup.js"></script>
  </body>
</html>

popup.js

document.addEventListener('DOMContentLoaded', function() {
   
  var getButton = document.getElementById('get-cookies');
  var cookieList = document.getElementById('cookie-list');

  getButton.addEventListener('click', function() {
   
    chrome.tabs.query({
   active: true, currentWindow: true}, function(tabs) {
   
      var url = tabs[0].url;
      chrome.cookies.getAll({
   url: url}, function(cookies) {
   
        cookieList.innerHTML = '';
        let cookiesText = '';
        for (var i = 0; i < cookies.length; i++) {
   
          var cookie = cookies[i];
          var li = document.createElement('li');
          li.textContent = cookie.name + '=' + cookie.value;
          cookieList.appendChild(li);
          cookiesText += li.textContent + '; ';
        }
      });
    });
  });
});

Pasted image 20231230220712

点击看执行效果
可以观察到,已经能把cookie带到端面了
Pasted image 20231230222639

3.把打印内容复制进剪切板

document.addEventListener('DOMContentLoaded', function() {
   
  var getButton = document.getElementById('get-cookies');
  var cookieList = document.getElementById('cookie-list');

  getButton.addEventListener('click', function() {
   
    chrome.tabs.query({
   active: true, currentWindow: true}, function(tabs) {
   
      var url = tabs[0].url;
      chrome.cookies.getAll({
   url: url}, function(cookies) {
   
        cookieList.innerHTML = '';
        let cookiesText = '';
        // 调整格式
        for (var i = 0; i < cookies.length; i++) {
   
          var cookie = cookies[i];
          var li = document.createElement('li');
          li.textContent = cookie.name + '=' + cookie.value;
          cookieList.appendChild(li);
          cookiesText += li.textContent + '; ';
        }
        // 将获取到的 cookie 复制到剪切板
        navigator.clipboard.writeText(cookiesText).then(function() {
   
          console.log('Cookies copied to clipboard.');
        }, function(err) {
   
          console.error('Could not copy cookies to clipboard: ', err);
        });
      });
    });
  });
});

重新刷新插件测试
Pasted image 20231230224053

4.确认能够复制以后,整理cookie的格式,使cookie文本可以直接复制进postman使用。(合在上一步一起做了)

完善

1.加个图标
2.复制成功给个弹窗提示
3.端面完善

图标

{
   
  "manifest_version": 3,
  "name": "Cookie Tool",
  "version": "0.0.1",
  ...省略
  "action": {
   
    "default_title": "Get Current Page Cookies",// 鼠标移动到插件上提示内容
    "default_popup": "hello.html",
    "default_icon": "icon.png"// 自制的图标
  }
}

icon.png等文件放在同目录下
随便用个在线生成,调整成合适的像素尺寸即可

弹窗提示

<html>
  <head>
    <title>Get Current Page Cookies</title>
    <meta charset="UTF-8">
    <script src="popup.js"></script>
    <style>
    ... 省略
      #toast {
     
      ... 省略
        white-space: nowrap; /* 添加此行以保持 toast 文本在一行显示 */
      }
    </style>
  </head>
  <body>
    <ul>
      <li id="get-cookies">Get Cookies</li>
    </ul>
    <ul>
      <li id="get-other">Todo</li>
    </ul>
    <div id="toast"></div>
  </body>
</html>

源码

Pasted image 20231230233809

GitHub

https://github.com/wenterwang/CookieTool

manifest.json

{
   
  "manifest_version": 3,
  "name": "Cookie Tool",
  "version": "0.0.1",
  "author": "wenterwang",
  "permissions": [
    "cookies"
  ],
  "host_permissions": [
    "http://*/*",
    "https://*/*"
  ],
  "action": {
   
    "default_title": "Get Current Page Cookies",
    "default_popup": "hello.html",
    "default_icon": "icon.png"
  }
}

hello.html

插件的端面,前面介绍中有截图

<html>
  <head>
    <title>Get Current Page Cookies</title>
    <meta charset="UTF-8">
    <script src="popup.js"></script>
    <style>
      body {
     
        font-family: Arial, sans-serif;
        margin: 0;
        padding: 0;
        min-width: 200px;
      }
      ul {
     
        list-style: none;
        padding: 0;
      }
      li {
     
        padding: 10px;
        border-bottom: 1px solid #ddd;
      }
      li:last-child {
     
        border-bottom: none;
      }
      #toast {
     
        display: none;
        position: fixed;
        bottom: 10px;
        left: 50%;
        transform: translateX(-50%);
        background-color: #333;
        color: #fff;
        padding: 5px 10px;
        border-radius: 5px;
        white-space: nowrap; /* 添加此行以保持 toast 文本在一行显示 */
      }
    </style>
  </head>
  <body>
    <ul>
      <li id="get-cookies">Get Cookies</li>
    </ul>
    <ul>
      <li id="get-other">Todo</li>
    </ul>
    <div id="toast"></div>
  </body>
</html>

popup.js

document.addEventListener('DOMContentLoaded', function() {
   
  var getButton = document.getElementById('get-cookies');
  var toast = document.getElementById('toast');

  function showToast(message) {
   
    toast.textContent = message;
    toast.style.display = 'block';
    setTimeout(function() {
   
      toast.style.display = 'none';
    }, 2000);
  }

  getButton.addEventListener('click', function() {
   
    chrome.tabs.query({
   active: true, currentWindow: true}, function(tabs) {
   
      var url = tabs[0].url;
      chrome.cookies.getAll({
   url: url}, function(cookies) {
   
        let cookiesText = '';
        for (var i = 0; i < cookies.length; i++) {
   
          var cookie = cookies[i];
          cookiesText += cookie.name + '=' + cookie.value + (i < cookies.length - 1 ? '; ' : '');
        }
        // 将获取到的 cookie 复制到剪切板
        navigator.clipboard.writeText(cookiesText).then(function() {
   
          showToast('Cookies copied to clipboard.');
        }, function(err) {
   
          console.error('Could not copy cookies to clipboard: ', err);
          showToast('Failed to copy cookies to clipboard.');
        });
      });
    });
  });
});

发布至Google Store

https://developer.chrome.com/docs/webstore/publish?hl=zh-cn

其他示例

chrome扩展示例
https://github.com/GoogleChrome/chrome-extensions-samples

相关推荐

  1. Chrome开发

    2024-01-02 04:42:01       31 阅读
  2. 开发Chrome入门

    2024-01-02 04:42:01       36 阅读
  3. Chrome 如何开发

    2024-01-02 04:42:01       32 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-01-02 04:42:01       94 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-01-02 04:42:01       100 阅读
  3. 在Django里面运行非项目文件

    2024-01-02 04:42:01       82 阅读
  4. Python语言-面向对象

    2024-01-02 04:42:01       91 阅读

热门阅读

  1. python的bytearray对象的使用

    2024-01-02 04:42:01       54 阅读
  2. jsp介绍

    jsp介绍

    2024-01-02 04:42:01      50 阅读
  3. 4种常见的跨域问题

    2024-01-02 04:42:01       49 阅读
  4. 疯狂程序员之重头暴学英语语法宝典!!!

    2024-01-02 04:42:01       50 阅读
  5. 使用TypeReference解析泛型数据类型

    2024-01-02 04:42:01       74 阅读
  6. I2C通信协议:设备互联的黄金标准

    2024-01-02 04:42:01       52 阅读
  7. 训练生成手写体数字 对抗神经网络

    2024-01-02 04:42:01       55 阅读
  8. 2024任务驱动Python程序设计讲课提纲

    2024-01-02 04:42:01       50 阅读
  9. go通过go run命令启动出现undefined

    2024-01-02 04:42:01       68 阅读