Chrome MV3声明NetRequest和X帧选项DENY

fhg3lkii  于 2022-12-20  发布在  Go
关注(0)|答案(1)|浏览(165)

我有一个带有chrome.webRequest的MV2扩展,它工作得很好,但是在MV3 declarativeNetRequest上失败了。
这个扩展就像一个多信使,为不同的站点打开多个iframe,将所有流行的信使合并到一个扩展中。
So I have a domain "example.com" and there I open multiple iframes, for example open an iframe with Twitter.com or Telegram.org. Since twitter.com or telegram.org set the X-Frame-Options to DENY those iframes don't show anything. With MV2 we could run chrome.webRequest and remove those headers:

chrome.webRequest.onHeadersReceived.addListener(
    function (details)
    {
        if (details.tabId && (details.tabId === tabId || details.tabId === -1 || tabMultiId.includes(details.tabId))) {
            var b = details.responseHeaders.filter((details) => !['x-frame-options', 'content-security-policy', 'x-content-security-policy', 'strict-transport-security', 'frame-ancestors'].includes(details.name.toLowerCase()));
            
            b.forEach(function(e){
              "set-cookie" === e.name &&  -1 !== e.value.indexOf("Secure") && (-1 !== e.value.indexOf("SameSite=Strict") ? 
                            (e.value = e.value.replace(/SameSite=Strict/g, "SameSite=None"))
                            : -1 !== e.value.indexOf("SameSite=Lax")
                            ? (e.value = e.value.replace(/SameSite=Lax/g, "SameSite=None"))
                            : (e.value = e.value.replace(/; Secure/g, "; SameSite=None; Secure")));
            });
            
            return {
                responseHeaders: b
            }
        }
    },
    {
        urls: [ "<all_urls>" ],
        tabId: tabId
    },
    ["blocking", "responseHeaders", "extraHeaders"]
);

我已经尝试做完全相同的mv3,但不断失败。我的2次尝试:

async function NetRequest() {
var blockUrls = ["*://*.twitter.com/*","*://*.telegram.org/*"];
var tabId = await getObjectFromLocalStorage('tabId');
var tabMultiId = [];
tabMultiId = JSON.parse(await getObjectFromLocalStorage('tabMultiId'));
tabMultiId.push(tabId);
blockUrls.forEach((domain, index) => {
    let id = index + 1;
    
        chrome.declarativeNetRequest.updateSessionRules({
        addRules:[
            {
            "id": id,
            "priority": 1,
            "action": {     "type": "modifyHeaders",
                            "responseHeaders": [
                                { "header": "X-Frame-Options", "operation": "remove" },
                                { "header": "Frame-Options", "operation": "remove" },
                                { "header": "content-security-policy", "operation": "remove" },
                                { "header": "content-security-policy-report-only", "operation": "remove" },
                                { "header": "x-content-security-policy", "operation": "remove" },
                                { "header": "strict-transport-security", "operation": "remove" },
                                { "header": "frame-ancestors", "operation": "remove" },
                                { "header": "set-cookie", "operation": "set", "value": "SameSite=None; Secure" }
                            ] 
            },
            "condition": {"urlFilter": domain, "resourceTypes": ["image","media","main_frame","sub_frame","stylesheet","script","font","xmlhttprequest","ping","websocket","other"], 
            "tabIds" : tabMultiId }
            }
            ],
        removeRuleIds: [id]
        });
    
});
}

async function launchWindow(newURL, windowDimensions, urlWindow, isIncognitoWindow, windowType) {
    chrome.windows.create({ url: newURL, type: windowType, incognito: isIncognitoWindow, width: windowDimensions.width, height: windowDimensions.height, left: windowDimensions.left, top: windowDimensions.top },
        async function (chromeWindow) {
            if (urlWindow != "install" || urlWindow != "update") {
                chrome.storage.local.set({ 'extensionWindowId': chromeWindow.id }, function () { });
                chrome.storage.local.set({ 'tabId': chromeWindow.tabs[0].id }, function () { });
                NetRequest();
            }
    });
}

还尝试:

const iframeHosts = [
        'twitter.com', 'telegram.org'
      ];

      const RULE = {
        id: 1,
        condition: {
          initiatorDomains: ['example.com'],
          requestDomains: iframeHosts,
          resourceTypes: ['sub_frame', 'main_frame'],
        },
        action: {
          type: 'modifyHeaders',
          responseHeaders: [
            {header: 'X-Frame-Options', operation: 'remove'},
            {header: 'Frame-Options', operation: 'remove'},
          ],
        },
      };
      chrome.declarativeNetRequest.updateDynamicRules({
        removeRuleIds: [RULE.id],
        addRules: [RULE],
      });

权限:

"permissions": [
    "system.display",
    "scripting",
    "activeTab",
    "notifications",
    "contextMenus",
    "unlimitedStorage",
    "storage",
    "declarativeNetRequestWithHostAccess",
    "webNavigation",
  "alarms"
  ],
  "host_permissions": [
  "<all_urls>"
  ],

任何这样的尝试都起作用了。问候并非常感谢任何试图提供帮助的人。

tjrkku2a

tjrkku2a1#

1.您需要使用chrome.browsingData API注销站点的service worker并清除其缓存。

  1. urlFilter的语法不同,因此您的"*://*.twitter.com/*"不正确,应该是"||twitter.com/",但是更好的解决方案是使用requestDomains,因为它允许在一个规则中指定多个站点。
    //清单. json
"permissions": ["browsingData", "declarativeNetRequest"],
  "host_permissions": ["*://*.twitter.com/", "*://*.telegram.org/"],

//扩展脚本

async function configureNetRequest(tabId) {
  const domains = [
    'twitter.com',
    'telegram.org',
  ];
  const headers = [
    'X-Frame-Options',
    'Frame-Options',
  ];
  await chrome.declarativeNetRequest.updateSessionRules({
    removeRuleIds: [1],
    addRules: [{
      id: 1,
      action: {
        type: 'modifyHeaders',
        responseHeaders: headers.map(h => ({ header: h, operation: 'remove'})),
      },
      condition: {
        requestDomains: domains,
        resourceTypes: ['sub_frame'],
        tabIds: [tabId],
      },
    }],
  });
  await chrome.browsingData.remove({
    origins: domains.map(d => `https://${d}`),
  }, {
    cacheStorage: true,
    serviceWorkers: true,
  });
}

//使用方法

chrome.windows.create({ url: 'about:blank' }, async w => {
  await configureNetRequest(w.tabs[0].id);
  await chrome.tabs.update(w.tabs[0].id, { url: 'https://some.real.url/' });
});

相关问题