代码之家  ›  专栏  ›  技术社区  ›  Kwang Sing

在chrome扩展中为请求添加前缀的正确设置是什么?

  •  0
  • Kwang Sing  · 技术社区  · 11 月前

    多年来,我通常在代理和重定向方面遇到困难,当我试图制作一个chrome扩展程序时。

    现在我正在用“chrome.declarativeNetRequest”制作一个清单v3扩展, 而不是使用“chrome.webRequest”,它很快就不会再出现了。

    稍后,我将尝试使用URL路径进行动态预测

    但即使是静态规则也没有运气,它代理了所有的网站,而不仅仅是我在代码中声明的域名。
    结果应该是

    GET https://www.dmm.com/things
    进入之内
    GET https://kcwiki.github.io/cache/things

    最后。但我的误解是什么?

    这是密码

    {
        "manifest_version": 3,
        "name": "Dynamic Declarative Redirect Extension",
        "version": "1.0",
        "permissions": [
            "declarativeNetRequest"
        ],
        "host_permissions": [
            "file:///*",
            "*://*.dmm.com/*"
        ],
        "background": {
            "service_worker": "background.js"
        },
        "web_accessible_resources": [
            {
                "resources": [
                    "*/*"
                ],
                "matches": [
                    "*://www.dmm.com/*",
                    "*://osapi.dmm.com/*",
                    "*://kcwiki.github.io/*"
                ]
            }
        ]
    }
    
    const initialRules = [
        {
            id: 1,
            priority: 1,
            action: {
                type: 'redirect',
                redirect: {
                    url: 'https://kcwiki.github.io/cache'
                }
            },
            condition: {
                urlFilter: '*://test.example.com/*',
                resourceTypes: ["main_frame"]
            }
        }
    ];
    chrome.runtime.onInstalled.addListener(async () => {
        // Get arrays containing new and old rules
        const oldRules = await chrome.declarativeNetRequest.getDynamicRules();
        const oldRuleIds = oldRules.map(rule => rule.id);
    
        await chrome.declarativeNetRequest.updateDynamicRules({
            removeRuleIds: oldRuleIds
        }, async () => {
            await chrome.declarativeNetRequest.updateDynamicRules({
                addRules: initialRules
            }, () => {
                console.log("Rule Set")
            });
        });
    })
    

    答案代码示例并标记我的错误。

    1 回复  |  直到 11 月前
        1
  •  1
  •   woxxom    11 月前
    1. 重定向时,您的 "host_permissions" 必须包括源站点和目标站点。
    2. 要更改URL的某些部分,请使用regexFilter+regexSubstitution。
    3. 为了避免安装警告“此扩展可以阻止任何URL”,请在中使用“declarativeNetRequestWithHostAccess”而不是“declarative NetRequest” "permissions"

    //manifest.json

      "permissions": ["declarativeNetRequestWithHostAccess"],
      "host_permissions": ["file:///*", "*://*.dmm.com/", "https://kcwiki.github.io/"],
    

    //背景.js

    const initialRules = [{
      id: 1,
      action: {
        type: 'redirect',
        redirect: {
          regexSubstitution: 'https://kcwiki.github.io/cache/\\1',
        },
      },
      condition: {
        requestDomains: ['www.dmm.com'],
        regexFilter: '^https?://www\\.dmm\\.com/(.*)',
        resourceTypes: ['main_frame'],
      },
    }];