chrome插件,修改对应URL的http请求的header头,包括ajax请求

要创建一个可以灵活修改HTTP请求头的Chrome扩展,包括一个用户界面来动态设置头部名称和值,可以按照以下步骤进行。我们会用到 chrome.storage API 来保存用户的设置,并在后台脚本中使用这些设置来修改请求头。

文件结构

my_chrome_extension/
│
├── icons/
│   ├── icon16.png
│   ├── icon48.png
│   └── icon128.png
│
├── background.js
├── manifest.json
├── options.html
├── options.js
├── popup.html
├── popup.js
├── popup.css
├── options.css

manifest.json

{
  "manifest_version": 2,
  "name": "Flexible HTTP Headers Modifier",
  "version": "1.0",
  "description": "A Chrome extension to modify HTTP headers with user-defined values",
  "permissions": [
    "storage",
    "webRequest",
    "webRequestBlocking",
    "<all_urls>"
  ],
  "background": {
    "scripts": ["background.js"]
  },
  "options_page": "options.html",
  "browser_action": {
    "default_popup": "popup.html",
    "default_icon": {
      "16": "icons/icon16.png",
      "48": "icons/icon48.png",
      "128": "icons/icon128.png"
    }
  },
  "icons": {
    "16": "icons/icon16.png",
    "48": "icons/icon48.png",
    "128": "icons/icon128.png"
  }
}

background.js

let customHeaders = {};
let urlPattern = '';

chrome.runtime.onInstalled.addListener(() => {
  chrome.storage.sync.get(['urlPattern', 'headers', 'values'], function(result) {
    if (result.urlPattern) {
      urlPattern = result.urlPattern;
    }
    if (result.headers && result.values) {
      for (let i = 0; i < result.headers.length; i++) {
        customHeaders[result.headers[i]] = result.values[i];
      }
    }
  });
});

chrome.webRequest.onBeforeSendHeaders.addListener(
  function(details) {
    if (details.url.match(new RegExp(urlPattern))) {
      for (const [name, value] of Object.entries(customHeaders)) {
        let headerExists = false;
        for (let header of details.requestHeaders) {
          if (header.name.toLowerCase() === name.toLowerCase()) {
            header.value = value;
            headerExists = true;
            break;
          }
        }
        if (!headerExists) {
          details.requestHeaders.push({ name: name, value: value });
        }
      }
    }
    return { requestHeaders: details.requestHeaders };
  },
  { urls: ["<all_urls>"] },
  ["blocking", "requestHeaders"]
);

chrome.storage.onChanged.addListener(function(changes, namespace) {
  if (namespace === 'sync') {
    if (changes.urlPattern) {
      urlPattern = changes.urlPattern.newValue;
    }
    if (changes.headers && changes.values) {
      customHeaders = {};
      for (let i = 0; i < changes.headers.newValue.length; i++) {
        customHeaders[changes.headers.newValue[i]] = changes.values.newValue[i];
      }
    }
  }
});

options.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Extension Options</title>
    <link rel="stylesheet" href="options.css">
</head>
<body>
    <div class="container">
        <h1>Modify HTTP Headers</h1>
        <div class="url-pattern">
            <label for="url-pattern-input">URL Pattern:</label>
            <input type="text" id="url-pattern-input" placeholder="URL Pattern">
        </div>
        <table id="headers-table">
            <thead>
                <tr>
                    <th>Header Name</th>
                    <th>Header Value</th>
                    <th>Actions</th>
                </tr>
            </thead>
            <tbody id="headers-container">
                <!-- Header entries will be dynamically added here -->
            </tbody>
        </table>
        <div class="buttons">
            <button id="add-header">Add Header</button>
            <button id="save-headers">Save Headers</button>
        </div>
    </div>
    <script src="options.js"></script>
</body>
</html>

options.js

document.addEventListener('DOMContentLoaded', function() {
    const headersContainer = document.getElementById('headers-container');
    const addHeaderButton = document.getElementById('add-header');
    const saveHeadersButton = document.getElementById('save-headers');

    addHeaderButton.addEventListener('click', function() {
        const headerEntry = document.createElement('tr');
        headerEntry.className = 'header-entry';
        headerEntry.innerHTML = `
            <td><input type="text" placeholder="Header Name" class="header-name"></td>
            <td><input type="text" placeholder="Header Value" class="header-value"></td>
            <td><button class="remove-header">Remove</button></td>
        `;
        headerEntry.querySelector('.remove-header').addEventListener('click', function() {
            headerEntry.remove();
        });
        headersContainer.appendChild(headerEntry);
    });

    saveHeadersButton.addEventListener('click', function() {
        const headers = [];
        const values = [];
        document.querySelectorAll('.header-entry').forEach(entry => {
            const name = entry.querySelector('.header-name').value;
            const value = entry.querySelector('.header-value').value;
            if (name && value) {
                headers.push(name);
                values.push(value);
            }
        });
        const urlPattern = document.getElementById('url-pattern-input').value;
        chrome.storage.sync.set({urlPattern: urlPattern, headers: headers, values: values}, function() {
            alert('Headers saved');
        });
    });

    chrome.storage.sync.get(['urlPattern', 'headers', 'values'], function(result) {
        if (result.urlPattern) {
            document.getElementById('url-pattern-input').value = result.urlPattern;
        }
        if (result.headers && result.values) {
            for (let i = 0; i < result.headers.length; i++) {
                const headerEntry = document.createElement('tr');
                headerEntry.className = 'header-entry';
                headerEntry.innerHTML = `
                    <td><input type="text" value="${result.headers[i]}" class="header-name"></td>
                    <td><input type="text" value="${result.values[i]}" class="header-value"></td>
                    <td><button class="remove-header">Remove</button></td>
                `;
                headerEntry.querySelector('.remove-header').addEventListener('click', function() {
                    headerEntry.remove();
                });
                headersContainer.appendChild(headerEntry);
            }
        }
    });
});

popup.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Popup</title>
    <link rel="stylesheet" href="popup.css">
</head>
<body>
    <h1>Modify HTTP Headers</h1>
    <button id="open-options">Open Options</button>
    <script src="popup.js"></script>
</body>
</html>

popup.js

document.addEventListener('DOMContentLoaded', function() {
    document.getElementById('open-options').addEventListener('click', function() {
        chrome.runtime.openOptionsPage();
    });
});

popup.css

body {
    width: 200px;
    font-family: Arial, sans-serif;
    margin: 0;
    padding: 20px;
    box-sizing: border-box;
}

h1 {
    font-size: 16px;
    margin: 0 0 20px;
    text-align: center;
}

button {
    display: block;
    width: 100%;
    margin: 10px 0;
    padding: 10px;
    font-size: 14px;
    cursor: pointer;
}

#open-options {
    background-color: #4CAF50; /* Green */
    border: none;
    color: white;
    padding: 15px 32px;
    text-align: center;
    text-decoration: none;
    display: inline-block;
    font-size: 16px;
}

options.css

.container {
    width: 800px;
    margin: 20px auto;
    padding: 20px;
    border: 1px solid #ccc;
    border-radius: 5px;
    box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}

h1 {
    font-size: 20px;
    margin-bottom: 20px;
    text-align: center;
}

.url-pattern {
    margin-bottom: 20px;
}

.url-pattern label {
    margin-right: 10px;
}

input[type="text"] {
    width: 96%;
    padding: 10px;
    margin-bottom: 10px;
    border: 1px solid #ccc;
    border-radius: 5px;
}

#headers-table {
    width: 100%;
    border-collapse: collapse;
    border: none; /* 移除表格的边框 */
}

#headers-table th, #headers-table td {
    border: 1px solid #ccc;
    padding: 10px;
    text-align: center;
}

#headers-table th {
    background-color: #f2f2f2; /* 添加表头背景色 */
}

#headers-table td input[type="text"] {
    width: calc(100% - 20px); /* 考虑到内边距,调整输入框的宽度 */
    padding: 8px;
    margin: 0;
    border: none; /* 移除输入框的边框 */
    border-radius: 5px;
    box-sizing: border-box;
}

.buttons {
    margin-top: 20px;
    text-align: center;
}

.buttons button {
    margin: 0 10px;
    padding: 10px 20px;
    font-size: 16px;
    cursor: pointer;
    border: none;
    border-radius: 5px;
    background-color: #4CAF50;
    color: white;
}

.buttons button:hover {
    background-color: #45a049;
}

加载和测试扩展

  1. 打开 Chrome 浏览器。
  2. 进入 chrome://extensions/ 页面。
  3. 打开右上角的“开发者模式”。
  4. 点击“加载已解压的扩展程序”按钮。
  5. 选择你的扩展所在的目录 my_chrome_extension

现在,你可以通过扩展的图标打开选项页面,添加或移除请求头。保存后,这些头会在所有的HTTP请求(包括AJAX请求)中被修改。

你可以写一段简单的说明,介绍用户如何使用 url-pattern,并提供一些示例。以下是一个可能的写作方式:


URL 匹配模式说明

URL 匹配模式允许您指定哪些 URL 将受到您自定义的 HTTP 标头的影响。这些模式采用简单的通配符形式,允许您根据需要指定匹配的 URL。

基本语法:
  • *:匹配任意字符序列(包括空字符)
  • ?:匹配单个字符
示例:
  • example.com:匹配 http://example.com/https://example.com/
  • *.example.com:匹配 http://sub.example.com/https://www.example.com/
  • https://example.com/*:仅匹配以 https://example.com/ 开头的 URL,包括其所有子路径
注意事项:
  • 匹配模式将应用于所有 HTTP 请求,包括页面加载、AJAX 请求等。
  • 要确保匹配模式的准确性和有效性,请测试您的规则并进行必要的调整。

你可以根据实际需要调整和扩展这个说明。

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mfbz.cn/a/744589.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

ActiViz集成到WPF中的空域问题

文章目录 一、场景1、WPF控件2、集成ActiViz或者VTK 二、问题1、需求2、空域问题 三、解决方案1、用WindowsFormsHost包裹住ElementHost&#xff0c;然后将WPF的控件放在ElementHost职中&#xff1a;2、用Window或者Popup去悬浮3、使用第三方库Microsoft.DwayneNeed&#xff08…

springcloud-gateway 路由加载流程

问题 Spring Cloud Gateway版本是2.2.9.RELEASE&#xff0c;原本项目中依赖服务自动发现来自动配置路由到微服务的&#xff0c;但是发现将spring.cloud.gateway.discovery.locator.enabledfalse 启动之后Gateway依然会将所有微服务自动注册到路由中&#xff0c;百思不得其解&a…

NineData和华为云在一起!提供一站式智能数据库DevOps平台

以GuassDB数据库为底座 NineData和华为云一起 为企业提供 一站式智能数据库DevOps平台 帮助开发者 高效、安全地完成 数据库SQL审核 访问控制、敏感数据保护等 日常数据库相关开发任务 NineData 智能数据管理平台 NineData 作为新一代的云原生智能数据管理平台&#xf…

Js逆向爬虫基础篇

这里写自定义目录标题 逆向技巧断点一 、请求入口定位1. 关键字搜索2. 请求堆栈3. hook4. JSON.stringify 二、响应入口定位&#xff1a;1. 关键字搜索2. hook3. JSON.parse 逆向技巧 断点 普通断点 条件断点 日志断点 XHR断点 一 、请求入口定位 1. 关键字搜索 key关…

【因果推断python】57_The Difference-in-Differences 3

目录 3) Enlightenment: A Flexible Functional Form Key Concepts 3) Enlightenment: A Flexible Functional Form 有好消息也有坏消息。首先是好消息&#xff1a;我们已经发现问题与函数形式有关&#xff0c;因此我们可以通过修正函数形式来解决这个问题。也就是说&#xf…

竞赛选题 python+大数据校园卡数据分析

0 前言 &#x1f525; 优质竞赛项目系列&#xff0c;今天要分享的是 &#x1f6a9; 基于yolov5的深度学习车牌识别系统实现 &#x1f947;学长这里给一个题目综合评分(每项满分5分) 难度系数&#xff1a;4分工作量&#xff1a;4分创新点&#xff1a;3分 该项目较为新颖&am…

短视频最佳时长:成都柏煜文化传媒有限公司

探索时间与内容之间的完美平衡 成都柏煜文化传媒有限公司 在数字媒体日益繁荣的今天&#xff0c;短视频已成为人们获取信息、娱乐休闲的重要形式。然而&#xff0c;关于短视频的最佳时长&#xff0c;一直是一个备受争议的话题。本文将探讨短视频时长的各种考量因素&#xff0…

基于MATLAB对线阵天线进行道尔夫—切比雪夫加权

相控阵天线——基于MATLAB对线阵进行道尔夫—切比雪夫加权 目录 前言 一、阵列天线的综合 二、道尔夫—切比雪夫综合 三、单元间距的改变对切比雪夫阵列方向图的影响 四、单元数的改变对切比雪夫阵列激励分布的影响 五、副瓣电平SLL对切比雪夫阵列激励幅度的影响 六、副…

深入理解Java中的Collectors(Stream流)

引言 在 Java 的 Stream API 中&#xff0c;Collectors 是一个非常强大的工具类&#xff0c;它提供了许多静态方法&#xff0c;用于将 Stream 的元素收集到集合、字符串或其他类型的结果中。使用 Collectors&#xff0c;我们可以轻松地进行数据聚合和转换操作。 文章目录 引言…

小区业主管理系统

摘 要 随着城市化进程的加速和人口的不断增加&#xff0c;小区的数量也在不断增加。小区作为城市居民居住的主要场所&#xff0c;其管理工作也变得越来越重要。传统的小区业主管理方式存在诸多问题&#xff0c;如信息传递不畅、业务处理效率低下等。因此&#xff0c;开发一个高…

Spring底层原理之FactoryBean Bean工厂 单例对象 多例对象

FactoryBean 在 Spring Framework 中&#xff0c;FactoryBean 是一个用于创建其他 Bean 实例的特殊工厂 Bean。它允许开发者自定义 Bean 的创建逻辑&#xff0c;从而更加灵活地管理和配置 Bean 的实例化过程。 FactoryBean 接口 FactoryBean 接口是 Spring 框架中的一个重要…

启动VMWare虚拟机报错

1. 无法打开内核设备“\\.\VMCIDev\VMX”: 操作成功完成。是否在安装 VMware Workstation 后重新引导? 模块“DevicePowerOn”启动失败。 未能启动虚拟机。 解决办法: 解决办法: 将 Ubuntu 64 位.vmx 找到vmci0.present"TRUE"这行改成 vmci0.present "FAL…

【AI编译器】triton学习:矩阵乘优化

Matrix Multiplication 主要内容&#xff1a; 块级矩阵乘法 多维指针算术 重新编排程序以提升L2缓存命 自动性能调整 Motivations 矩阵乘法是当今高性能计算系统的一个关键组件&#xff0c;在大多数情况下被用于构建硬件。由于该操作特别复杂&#xff0c;因此通常由软件提…

fail2ban自动屏蔽之jumpserver

fail2ban是一款实用软件&#xff0c;可以监视你的系统日志&#xff0c;然后匹配日志的错误信息&#xff08;正则式匹配&#xff09;执行相应的屏蔽动作。 jumpserver是一款开源堡垒机&#xff0c;其拥有一定的防护登录&#xff0c;也可以做登录限制&#xff0c;但是相对于防火…

湖南(用户画像)源点调研 适用于新产品开发的市场调研方法

湖南&#xff08;上市验证调研&#xff09;源点咨询认为&#xff1a;其实市场与用户研究的方法不管都什么花哨的名头&#xff0c;本质上只有两种&#xff1a;定量与定性。而对于新产品的开发最重要的就是掌握好定性的研究方法。 问&#xff1a;对于新产品开发我们面对的是什么…

js如何使得四舍五入的百分比之和为100%

在JavaScript中&#xff0c;如果你想要确保一组四舍五入后的百分比之和严格等于100%&#xff0c;那么你不能直接对每个百分比进行四舍五入&#xff0c;因为四舍五入会引入误差。但是&#xff0c;你可以采用一种策略&#xff0c;即先对所有的百分比进行常规的四舍五入&#xff0…

SNEC天合储能秀:全球首发多元场景一站式工商业储能融合解决方案

6月13日-15日&#xff0c;SNEC2024光伏与智慧能源展在上海隆重举行&#xff0c;来自全球95个国家和地区3000家国内外展商齐聚展会&#xff0c;5000行业专家共话产业发展。致力于成为全球光储智慧能源解决方案的领导者&#xff0c;天合光能&#xff08;展位号&#xff1a;7.2H-E…

线性和二次判别分析

线性判别分析 线性判别分析&#xff08;Linear Discriminant Analysis&#xff0c;LDA&#xff09;亦称 Fisher 判别分析。其基本思想是&#xff1a;将训练样本投影到低维超平面上&#xff0c;使得同类的样例尽可能近&#xff0c;不同类的样例尽可能远。在对新样本进行分类时&…

测试行业,你的未来路在何方?失业之外,暗藏的这个危机更可怕!

目前测试行业现状 近期飞书的大规模裁员&#xff0c;无疑为2024年伊始蒙上了一层阴影。再加上“共享员工”模式的兴起&#xff0c;对于身处互联网行业的从业者来说&#xff0c;无疑是雪上加霜。 此外&#xff0c;延续了2023年的情况&#xff0c;在求职平台如BOSS直聘上&#…

基于Java的宠物领养管理系统【附源码】

摘 要 近些年来&#xff0c;随着科技的飞速发展&#xff0c;互联网的普及逐渐延伸到各行各业中&#xff0c;给人们生活带来了十分的便利&#xff0c;宠物管理系统利用计算机网络实现信息化管理&#xff0c;使整个宠物领养的发展和服务水平有显著提升。 本文拟采用IDEA开发工具…