询问 chrome 扩展。如何阻止文件下载

问题描述 投票:0回答:1
// background.js
chrome.webRequest.onBeforeRequest.addListener(
  blockDownloads,
  { urls: ["<all_urls>"], types: ["main_frame", "sub_frame"] },
  ["blocking"]
);

function blockDownloads(details) {
  
  if (isDownloadRequest(details)) {
    
    return { cancel: true };
  }
}
// manifest.json
{
  "manifest_version": 3,
  "name": "Block Downloads",
  "version": "1.0",
  "description": "Block all downloads on web pages",
  "permissions": ["webRequest", "webRequestBlocking", "activeTab"],
  "background": {
    "service_worker": "background.js"
  },
  "action": {
    "default_popup": "popup.html",
    "default_icon": {
      "16": "icon16.png",
      "48": "icon48.png",
      "128": "icon128.png"
    }
  },
  "icons": {
    "16": "icon16.png",
    "48": "icon48.png",
    "128": "icon128.png"
  },
  "host_permissions": ["<all_urls>"]
}

错误内容

未选中的runtime.lastError:您无权使用阻塞的webRequest侦听器。请务必在清单中声明 webRequestBlocking 权限。

请帮我改正

我尝试将它们编辑成这样

{
  "name": "Download Blocker",
  "version": "1.1",
  "description": "Blocks file downloads (declarative approach)",
  "manifest_version": 3,
  "permissions": [
    "declarativeNetRequest",
    "webRequest" // Needed for observing requests
  ],
  "background": {
    "service_worker": "background.js"
  },
  "declarativeNetRequest": {
    "rules": [
      {
        "id": "blockDownloads",
        "priority": 1,
        "condition": {
          "url": {
            "pathSuffix": ".pdf" // Assuming you want to block PDFs
          },
          "types": ["main_frame", "sub_frame", "stylesheet", "script", "image", "object", "xhr", "ping", "other"] // Block all request types
        },
        "action": {
          "type": "cancel"
        }
      }
    ]
  }
}

但是有一个错误

无法识别清单键“declarativeNetRequest”。

请帮我改正

javascript google-chrome-extension
1个回答
0
投票

要修复此错误,请确保您已在

webRequest
中正确声明了
webRequestBlocking
manifest.json
权限。此外,Chrome Extensions Manifest V3 需要使用 Service Worker 而不是后台页面。从您的代码来看,您似乎已经在这样做了,这很棒。该错误可能源于未正确声明权限。仔细检查您的
manifest.json
权限部分是否有任何拼写错误或错误。另外,请确保您在支持 Manifest V3 的 Chrome 版本中测试您的扩展程序。

© www.soinside.com 2019 - 2024. All rights reserved.