[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"$f3ttk8komhdyw4":3,"portal-md-616fbcc2e053ca97a181d2306c71052f":600},{"code":4,"data":5},2000,{"sectionUuid":6,"section":7,"prev":598,"next":599},"616fbcc2e053ca97a181d2306c71052f",{"uuid":6,"name":8,"category":9,"menu":10},"浏览器插件开发","大前端",[11,61,105,561,574],{"id":12,"isCategory":13,"label":14,"children":15,"access":24},14,true,"浏览器插件（扩展）开发教程",[16,20,25,29,33,37,41,45,49,53,57],{"id":17,"path":6,"label":18,"access":19},2,"Chrome V3浏览器插件（扩展程序）开发介绍","free",{"id":21,"path":22,"label":23,"access":24},3,"7d248dd2026017ac23fe2c045d31daa7","浏览器插件开发环境搭建","vip",{"id":26,"path":27,"label":28,"access":24},4,"40f7e38312c4da0871af5bb30c06943b","插件的基本结构",{"id":30,"path":31,"label":32,"access":24},5,"9dfc7ed5b10b9b6b6fa3b1bfbd9059c4","解析清单文件manifest.json的参数",{"id":34,"path":35,"label":36,"access":24},6,"8361f3a53ea0008dbf7a2b39ee2e75b0","插件的用户界面弹出窗口（Popup）",{"id":38,"path":39,"label":40,"access":24},7,"8f972b91bca4f7ef48fdd481eedf8f2f","V3中常用的权限使用介绍",{"id":42,"path":43,"label":44,"access":24},8,"42ba66de4540e80f7beccefe48cd8dfb","处理事件",{"id":46,"path":47,"label":48,"access":24},9,"2a55e6ce7a6c3568c218789e49a93a45","与网页的交互",{"id":50,"path":51,"label":52,"access":24},10,"4312b6ad20d74055e28d4f075b68d09b","存储与数据管理",{"id":54,"path":55,"label":56,"access":24},11,"fc858c67c79da16d39fae7a34132ff23","网络请求与 API 调用",{"id":58,"path":59,"label":60,"access":24},12,"04c0a32ac124a57ec41006178b76f2ec","调试与测试",{"id":62,"isCategory":13,"label":63,"children":64,"access":24},27,"高级",[65,69,73,77,81,85,89,93,97,101],{"id":66,"path":67,"label":68,"access":24},16,"13f158642a95569952b9823ccf7becf9","Chrome 拦截、修改网络请求",{"id":70,"path":71,"label":72,"access":24},17,"586301ce88ea1188ae1abbf275e2fdef","Chrome 获取指定网站的Cookie并存储起来",{"id":74,"path":75,"label":76,"access":24},18,"40fd5bd5efb340fd27d70917d3d4e910","Chrome 无视跨域从第三方接口获取数据",{"id":78,"path":79,"label":80,"access":24},19,"be4f00e145901ac90cbf5b63f0e8a6ec","使用Vue2开发Chrome插件",{"id":82,"path":83,"label":84,"access":24},20,"36909dafc5335da3804693d6a1987d25","Vue3 vite开发浏览器插件",{"id":86,"path":87,"label":88,"access":24},21,"d3dfc39a43ed2c3ffa4f449259156afd","插件的安全性与权限控制",{"id":90,"path":91,"label":92,"access":24},22,"c80b382b061336405aaf7d9c4e01cde5","性能优化与资源管理",{"id":94,"path":95,"label":96,"access":24},23,"9b5d7d4208cbd39541ea7ffefc77973e","避免常见错误与陷阱",{"id":98,"path":99,"label":100,"access":24},24,"d29d551e121e4651d007b29b0c743830","V2和V3的插件开发区别对比",{"id":102,"path":103,"label":104,"access":24},25,"5c9d10ede1a36d7031514316cf45678d","V2插件升级到V3",{"id":106,"isCategory":13,"label":107,"children":108,"access":24},144,"V3 API",[109,113,117,121,125,129,132,136,140,144,148,152,156,160,164,168,172,176,180,184,188,192,196,200,204,208,212,216,220,224,228,232,236,240,244,248,252,256,260,263,267,271,275,279,283,287,291,295,299,303,307,311,315,319,323,327,331,335,339,343,347,351,355,359,363,367,371,374,378,382,386,390,393,397,401,405,409,413,417,421,425,429,433,437,441,445,449,453,457,461,465,469,473,477,481,485,489,493,497,501,505,509,513,517,521,525,529,533,537,541,545,549,553,557],{"id":110,"path":111,"label":112,"access":24},29,"e070e99862ff55e65e25140ce377b2bb","chrome.browser",{"id":114,"path":115,"label":116,"access":24},30,"a4ae45c1e8c23eae7365ede5f64c4c7b","chrome.browseraction",{"id":118,"path":119,"label":120,"access":24},31,"ae101cbee0f654f1b818371ee8e14207","chrome.extension",{"id":122,"path":123,"label":124,"access":24},32,"56e44be4213a7f77bb111c49acace75a","chrome.notifications",{"id":126,"path":127,"label":128,"access":24},33,"12d3b5bf5361b2662cb9cfd8e25d030d","chrome.runtime",{"id":130,"path":51,"label":131,"access":24},34,"chrome.storage",{"id":133,"path":134,"label":135,"access":24},35,"83bfc536abdebfa4fb43e22049808399","chrome.tabs",{"id":137,"path":138,"label":139,"access":24},36,"be5af3834d6f36bfdd754c339c74fba7","chrome.warning",{"id":141,"path":142,"label":143,"access":24},37,"bd7934e89ba046466cb44755df34eef7","chrome.accessibilityFeature",{"id":145,"path":146,"label":147,"access":24},38,"a50cd5fa225cdeb1d3b3a2d678ae746b","chrome.action",{"id":149,"path":150,"label":151,"access":24},39,"6419a8af43880209089e0ab469c526ca","chrome.alarms",{"id":153,"path":154,"label":155,"access":24},40,"6c20665c139083f1c16f7e36934553b1","chrome.audio",{"id":157,"path":158,"label":159,"access":24},41,"6fe5b2394888de3ea925719bafa4de31","chrome.bookmarks",{"id":161,"path":162,"label":163,"access":24},42,"cb7679091795c54633f397a2583d08b9","chrome.browsingData",{"id":165,"path":166,"label":167,"access":24},43,"6f115d179ab7eb0a5bc24e858ecbab40","chrome.certificateProvider",{"id":169,"path":170,"label":171,"access":24},44,"55463adb19e3a05f95aa1505993bd57c","chrome.commands",{"id":173,"path":174,"label":175,"access":24},45,"7c2927a200c7c09096d790e4fdce9f60","chrome.contentSettings",{"id":177,"path":178,"label":179,"access":24},46,"6dfdb20db29c24e9dd295a85fae062b9","chrome.contextMenus",{"id":181,"path":182,"label":183,"access":24},47,"17289fe79f1b8ed217b18a316fff5b46","chrome.cookies",{"id":185,"path":186,"label":187,"access":24},48,"8a30a57ed8d1d977a9e7b96fad3620e3","chrome.debugger",{"id":189,"path":190,"label":191,"access":24},49,"5affbcc8da4866f4cb51237cf14238d3","chrome.declarativeContent",{"id":193,"path":194,"label":195,"access":24},50,"aa39f73e5904e0b156786f2593a40fc8","chrome.declarativeNetRequest",{"id":197,"path":198,"label":199,"access":24},51,"82abc322f8c2f54c7412a6a8c2ca7609","chrome.desktopCapture",{"id":201,"path":202,"label":203,"access":24},52,"98dec6946fb737eef957a2d22d328758","chrome.devtools.inspectedWindow",{"id":205,"path":206,"label":207,"access":24},53,"adbb802e9de5efd9fe33f437cfdef7f3","chrome.devtools.network",{"id":209,"path":210,"label":211,"access":24},54,"3424d6fb628cab7d8457499499371752","chrome.devtools.panels",{"id":213,"path":214,"label":215,"access":24},55,"77c296db498644e930a3763ca020e3ed","chrome.devtools.performance",{"id":217,"path":218,"label":219,"access":24},56,"3924d9e6dab32782aefea299f78ce7c6","chrome.devtools.recorder",{"id":221,"path":222,"label":223,"access":24},57,"17fc328a824661af164581419cad6d95","chrome.dns",{"id":225,"path":226,"label":227,"access":24},58,"b4add39316f7d057e15a37889ddf4a51","chrome.documentScan",{"id":229,"path":230,"label":231,"access":24},59,"9b2fac97c705849f62d0a52ae48ca3aa","chrome.dom",{"id":233,"path":234,"label":235,"access":24},60,"ff743a4bccf4fa6f7b139379e046543b","chrome.downloads",{"id":237,"path":238,"label":239,"access":24},61,"6cc31b184231f73b4db3546f291db5be","chrome.enterprise.deviceAttributes",{"id":241,"path":242,"label":243,"access":24},62,"a696930aa627a3eddaed86ded8a9588f","chrome.enterprise.hardwarePlatform",{"id":245,"path":246,"label":247,"access":24},63,"e6c7dcaf6b1d7054c374db29cd5ad766","chrome.enterprise.login",{"id":249,"path":250,"label":251,"access":24},64,"a3637d2e82256d155830eecc66cdf1db","chrome.enterprise.networkingAttributes",{"id":253,"path":254,"label":255,"access":24},65,"6ad9135cbc131c61bebcf6765047d746","chrome.enterprise.platformKeys",{"id":257,"path":258,"label":259,"access":24},66,"80e93ca59d4a6e1a39eed213b2038c74","chrome.events",{"id":261,"path":262,"label":120,"access":24},67,"46f2dd90b91d385c4d7539eb19b50092",{"id":264,"path":265,"label":266,"access":24},68,"d7509251523f9e6f262bbd0f0c7b3c82","chrome.extensionTypes",{"id":268,"path":269,"label":270,"access":24},69,"97082220d5f9e61f22822042a0bb473a","chrome.fileBrowserHandler",{"id":272,"path":273,"label":274,"access":24},70,"dfba5e8c7e5e7b38a67b8364e3f63ac8","chrome.fileSystem",{"id":276,"path":277,"label":278,"access":24},71,"328aa0510092bed28fa4d9925568bc56","chrome.fileSystemProvider",{"id":280,"path":281,"label":282,"access":24},72,"dffe72a4205fbb3c40fd89749c88c208","chrome.fontSettings",{"id":284,"path":285,"label":286,"access":24},73,"560b1a62abd39f1068c8288ef3b5749e","chrome.gcm",{"id":288,"path":289,"label":290,"access":24},74,"e2bad5e7c1b56fedb8056813487f86da","chrome.history",{"id":292,"path":293,"label":294,"access":24},75,"7e8a51312df418417031448bf55d6771","chrome.i18n",{"id":296,"path":297,"label":298,"access":24},76,"53fadbe9296cc7514097adb776560201","chrome.identity",{"id":300,"path":301,"label":302,"access":24},77,"6f2a5de8e598771361fd679bd5320991","chrome.idle",{"id":304,"path":305,"label":306,"access":24},78,"d804b703a274b585f1e06f4376a826f3","chrome.input.ime",{"id":308,"path":309,"label":310,"access":24},79,"9806b5e626585653ec2a3865178bda6b","chrome.instanceID",{"id":312,"path":313,"label":314,"access":24},80,"a61c55ffe4a870a763400bd39a5848a6","chrome.loginState",{"id":316,"path":317,"label":318,"access":24},81,"fdbdd83bf45276ed3d107a9cd4c5d16f","chrome.management",{"id":320,"path":321,"label":322,"access":24},82,"1ba68e332a48de01e39b091356597d30","chrome.offscreen",{"id":324,"path":325,"label":326,"access":24},83,"83f11afd4c8184e2d0ece9b985a0ca1b","chrome.omnibox",{"id":328,"path":329,"label":330,"access":24},84,"4dbccf4eb5ca890b597169fbd21691d6","chrome.pageCapture",{"id":332,"path":333,"label":334,"access":24},85,"01c97154ae98c8cb16770ac87d586dc5","chrome.permissions",{"id":336,"path":337,"label":338,"access":24},86,"7552fb13f029d2e290bdd2d865fd05ab","chrome.platformKeys",{"id":340,"path":341,"label":342,"access":24},87,"3d81f7dd1249fa9cea2d85f6aa931149","chrome.power",{"id":344,"path":345,"label":346,"access":24},88,"819d64822a8326e2da024e781d9d33b8","chrome.printerProvider",{"id":348,"path":349,"label":350,"access":24},89,"728f388f9ab2e83389d2e902d4113385","chrome.printing",{"id":352,"path":353,"label":354,"access":24},90,"d333c85608fce2fdbb039bd80c3be82f","chrome.printingMetrics",{"id":356,"path":357,"label":358,"access":24},91,"984bd068cd6bf88e66c1ac7c9020eb65","chrome.privacy",{"id":360,"path":361,"label":362,"access":24},92,"c1c2bf2e6c378a29145ee1c3c5cab400","chrome.processes",{"id":364,"path":365,"label":366,"access":24},93,"7f1d412c60f2819c408d7ff2a4312909","chrome.proxy",{"id":368,"path":369,"label":370,"access":24},94,"a71a90830c166ed860cdf73753de2cd8","chrome.readingList",{"id":372,"path":373,"label":128,"access":24},95,"d5458fa2ec2059a91544985a98bb465c",{"id":375,"path":376,"label":377,"access":24},96,"796c594be668a64fd7dd5eead844fc07","chrome.scripting",{"id":379,"path":380,"label":381,"access":24},97,"497faed15fe7d8016d518b31b721860d","chrome.search",{"id":383,"path":384,"label":385,"access":24},98,"eecb83799127bc58ebf5c7eb6a6f64b0","chrome.sessions",{"id":387,"path":388,"label":389,"access":24},99,"c29e92ec9811bc4267564b1eb9ae9cdb","chrome.sidePanel",{"id":391,"path":392,"label":131,"access":24},100,"2f63b4b0a1429ecad94e4c90266d46f0",{"id":394,"path":395,"label":396,"access":24},101,"9fbfba3c6feae98a70b382a6cd902bfc","chrome.system.cpu",{"id":398,"path":399,"label":400,"access":24},102,"a1450d20066ad2cec538b9d1316727fb","chrome.system.display",{"id":402,"path":403,"label":404,"access":24},103,"2f528415b694b92dc4baa159d2a1880f","chrome.system.memory",{"id":406,"path":407,"label":408,"access":24},104,"22843a6fa9ce2c2459175fffbe2dccff","chrome.system.storage",{"id":410,"path":411,"label":412,"access":24},105,"b4d50fdd26094fe915924f8219e50c07","chrome.systemLog",{"id":414,"path":415,"label":416,"access":24},106,"80190b7e8cd401f4c9b47ed51ff3e60c","chrome.tabCapture",{"id":418,"path":419,"label":420,"access":24},107,"ab02b736f4e8a8317e8ffa341b38b342","chrome.tabGroups",{"id":422,"path":423,"label":424,"access":24},108,"4b40ca62677c11cd6c9f9e681bd7e70c","chrome.topSites",{"id":426,"path":427,"label":428,"access":24},109,"77cca8bce7a37d9f7ea1faa9b5b1da74","chrome.tts",{"id":430,"path":431,"label":432,"access":24},110,"078f21eace67af1d8bd1af95b520048b","chrome.ttsEngine",{"id":434,"path":435,"label":436,"access":24},111,"48f9aeef2b235cf9704b3809e50ab6b6","chrome.types",{"id":438,"path":439,"label":440,"access":24},112,"568fbdbac206d20af90f61670b200279","chrome.userScripts",{"id":442,"path":443,"label":444,"access":24},113,"eac24b51b86078e98925b9deede4fe91","chrome.vpnProvider",{"id":446,"path":447,"label":448,"access":24},114,"bcc1173c5f025d49371aa4afbdfcf7ca","chrome.wallpaper",{"id":450,"path":451,"label":452,"access":24},115,"4d109de2909895dfd219f2530f6cd24a","chrome.webAuthenticationProxy",{"id":454,"path":455,"label":456,"access":24},116,"f8aa13cde2704136de263b330d0cb513","chrome.webNavigation",{"id":458,"path":459,"label":460,"access":24},117,"80ab105eae88ad49f5f6397f5c5f8344","chrome.webRequest",{"id":462,"path":463,"label":464,"access":24},118,"30275e4a4c30fb6760b0efebd8591821","chrome.windows",{"id":466,"path":467,"label":468,"access":24},119,"4886a32cbf168b1a69ac7bda288c92e2","chrome.bluetooth",{"id":470,"path":471,"label":472,"access":24},120,"8807eee1d40bf6053810ec69c0d61119","chrome.bluetoothSocket",{"id":474,"path":475,"label":476,"access":24},121,"562dd9c9fa16d777b9b14ebb09a5dc88","chrome.mediaGalleries",{"id":478,"path":479,"label":480,"access":24},122,"3833569e5ebdf2fc14cee659f94b5057","chrome.app.window",{"id":482,"path":483,"label":484,"access":24},123,"7d963d093ce8aac5d7c2a632e3637d0a","chrome.mdns",{"id":486,"path":487,"label":488,"access":24},124,"f44e4243bfcb6b9f1a57889be4d78fa5","chrome.clipboard",{"id":490,"path":491,"label":492,"access":24},125,"2913d0700cd38135a18d10d47e882e8e","chrome.hid",{"id":494,"path":495,"label":496,"access":24},126,"f45c1b6a6377d177476b9c101e2b5b66","chrome.app.runtime",{"id":498,"path":499,"label":500,"access":24},127,"e6c05984bfb45b0d4890b1cb20d873c2","chrome.bluetoothLowEnergy",{"id":502,"path":503,"label":504,"access":24},128,"fdd9c2398683fb595d78bde43ed0229f","chrome.appviewTag",{"id":506,"path":507,"label":508,"access":24},129,"4603f51a9d3123142ceb34e472457d35","chrome.automation",{"id":510,"path":511,"label":512,"access":24},130,"fed46078749ad7bd75d61aca63b729c9","chrome.declarativeWebRequest",{"id":514,"path":515,"label":516,"access":24},131,"3878536ecbfda337ce2c28816c3dd1a1","chrome.networking.onc",{"id":518,"path":519,"label":520,"access":24},132,"5ea84ae1d1db080dd4f4339ee1dadb88","chrome.syncFileSystem",{"id":522,"path":523,"label":524,"access":24},133,"ca7e91c4f26463495e95925a73909e40","chrome.sockets.tcpServer",{"id":526,"path":527,"label":528,"access":24},134,"ef207f1f224857ff3605abd62ac23d00","chrome.sockets.udp",{"id":530,"path":531,"label":532,"access":24},135,"6b0b46911a4c57e4bfc619f4a8bbb3fc","chrome.sockets.tcp",{"id":534,"path":535,"label":536,"access":24},136,"06a0de982c71d0ccc6d3afddc3f0afcf","chrome.virtualKeyboard",{"id":538,"path":539,"label":540,"access":24},137,"99fffe1f518ad2edf5317e5fc91da9be","chrome.serial",{"id":542,"path":543,"label":544,"access":24},138,"690c7e38a06be2a36896da841b9e0e08","chrome.system.network",{"id":546,"path":547,"label":548,"access":24},139,"3bd3158481a9e345367d014acacbba00","chrome.socket",{"id":550,"path":551,"label":552,"access":24},140,"ea305d0e7b732c3f7db9e42fa648db52","chrome.usb",{"id":554,"path":555,"label":556,"access":24},141,"cce4abc92c2e10a0680874f1e0d00511","chrome.webviewTag",{"id":558,"path":559,"label":560,"access":24},142,"cc0ca79e6d7d61ef462f2a6c7bb74e45","chrome.pageAction",{"id":562,"isCategory":13,"label":563,"children":564,"access":24},149,"案例研究与项目开发",[565,570],{"id":566,"path":567,"label":568,"access":569},146,"c40c5a3cbd2442737e3bfc26caa78d86","CTO Plus技术服务栈官方插件","closed",{"id":571,"path":572,"label":573,"access":569},147,"257b948c356336d5d3db0e7442dc88d3","跨境电商自动化约号插件",{"id":575,"label":576,"children":577,"access":24},157,"扩展阅读",[578,582,585,589,592,595],{"id":579,"path":580,"label":581,"access":24},151,"","打包与发布(分发)插件",{"id":583,"path":580,"label":584,"access":24},152,"更新与版本管理",{"id":586,"path":587,"label":588,"access":569},153,"686d88d635071785dd00094143e32ac7","浏览器插件市场的申请与发布流程",{"id":590,"path":580,"label":591,"access":24},154,"浏览器插件开发的官方文档与学习资源",{"id":593,"path":580,"label":594,"access":24},155,"常见问题解答",{"id":596,"path":580,"label":597,"access":24},156,"浏览器插件开发社区资源与论坛",null,{"path":22,"label":23,"access":24},{"code":4,"msg":601,"data":602},"success",{"last_modify_datetime":603,"sys_article_tags":604,"custom_article_tags":605,"special_column":606,"title":609,"id":580,"markdown":610,"number_of_visits":608,"next_page_url":22,"next_page_title":23,"last_page_url":580,"last_page_title":580,"category_path":611},"2026-07-26 23:40:07",[],[],{"name":607,"article_nums":608,"subscribe_nums":608},"公众号：CTO Plus",0,"Chrome V3浏览器插件开发介绍","\n## 扩展程序基础概念\n\nChrome扩展程序是基于Web技术（HTML、CSS、JavaScript）构建的小型软件程序，用于定制Chrome浏览器的功能和行为。扩展程序通过Chrome扩展API与浏览器交互，提供增强的浏览体验。\n\nManifest V3是Chrome扩展平台的最新版本，于2020年推出，旨在提高扩展程序的安全性、隐私性和性能。与Manifest V2相比，V3引入了服务工作者替代后台页面、修改了网络请求处理方式，并增强了权限控制机制。\n\n扩展程序的基本架构包括清单文件（manifest.json）、内容脚本、后台服务工作者、弹出页面和选项页面等组件。这些组件协同工作，实现扩展程序的功能。\n\n## Manifest V3核心变更\n\n### 服务工作者替代后台页面\n\nManifest V3最重要的变化之一是使用服务工作者替代持久的后台页面。服务工作者是事件驱动的脚本，在需要时由浏览器激活，在空闲时终止，这显著减少了资源消耗。\n\n```javascript\n\u002F\u002F manifest.json中服务工作者声明\n{\n  \"background\": {\n    \"service_worker\": \"service-worker.js\"\n  }\n}\n```\n\n服务工作者与后台页面的主要区别在于生命周期管理。服务工作者在事件触发时激活，处理完成后可能被终止。开发者需要采用事件驱动的编程模式，使用chrome.storage API持久化状态，而不是依赖全局变量。\n\n### 声明式网络请求\n\nManifest V3使用declarativeNetRequest API替代webRequest API的阻塞能力，增强了隐私保护和性能。扩展程序声明规则，由浏览器直接处理网络请求，而不是通过扩展程序代码拦截每个请求。\n\n```javascript\n\u002F\u002F manifest.json中声明网络请求权限\n{\n  \"permissions\": [\n    \"declarativeNetRequest\"\n  ],\n  \"declarative_net_request\": {\n    \"rule_resources\": [\n      {\n        \"id\": \"ruleset_1\",\n        \"enabled\": true,\n        \"path\": \"rules.json\"\n      }\n    ]\n  }\n}\n```\n\n### 远程代码执行限制\n\nManifest V3禁止执行远程代码，所有JavaScript代码必须包含在扩展程序包内。这提高了安全性，防止恶意代码注入。扩展程序只能通过外部资源加载特定类型的内容，如图片、样式表和字体。\n\n```javascript\n\u002F\u002F 允许加载的外部资源\n{\n  \"content_security_policy\": {\n    \"extension_pages\": \"script-src 'self'; object-src 'self'\"\n  }\n}\n```\n\n## 扩展程序架构与组件\n\n### 清单文件配置\n\n清单文件是扩展程序的入口点，定义了扩展程序的基本信息、权限和功能组件。\n\n```json\n{\n  \"manifest_version\": 3,\n  \"name\": \"示例扩展\",\n  \"version\": \"1.0.0\",\n  \"description\": \"一个简单的Chrome扩展示例\",\n  \n  \"permissions\": [\n    \"activeTab\",\n    \"storage\",\n    \"scripting\"\n  ],\n  \n  \"host_permissions\": [\n    \"https:\u002F\u002F*.example.com\u002F*\"\n  ],\n  \n  \"background\": {\n    \"service_worker\": \"service-worker.js\"\n  },\n  \n  \"action\": {\n    \"default_popup\": \"popup.html\",\n    \"default_title\": \"点击打开弹出窗口\"\n  },\n  \n  \"content_scripts\": [\n    {\n      \"matches\": [\"https:\u002F\u002F*.example.com\u002F*\"],\n      \"js\": [\"content-script.js\"],\n      \"css\": [\"content-style.css\"]\n    }\n  ],\n  \n  \"options_page\": \"options.html\",\n  \n  \"web_accessible_resources\": [\n    {\n      \"resources\": [\"injected-script.js\"],\n      \"matches\": [\"https:\u002F\u002F*.example.com\u002F*\"]\n    }\n  ]\n}\n```\n\n### 服务工作者实现\n\n服务工作者处理扩展程序的事件和后台任务，如监听浏览器事件、管理状态和执行定期任务。\n\n```javascript\n\u002F\u002F service-worker.js\nchrome.runtime.onInstalled.addListener((details) => {\n  if (details.reason === 'install') {\n    \u002F\u002F 扩展程序首次安装\n    chrome.storage.local.set({ installed: true });\n    console.log('扩展程序已安装');\n  } else if (details.reason === 'update') {\n    \u002F\u002F 扩展程序更新\n    console.log('扩展程序已更新');\n  }\n});\n\n\u002F\u002F 监听标签页更新\nchrome.tabs.onUpdated.addListener((tabId, changeInfo, tab) => {\n  if (changeInfo.status === 'complete' && tab.url?.includes('example.com')) {\n    \u002F\u002F 向内容脚本发送消息\n    chrome.tabs.sendMessage(tabId, { action: 'pageLoaded' });\n  }\n});\n\n\u002F\u002F 处理来自内容脚本的消息\nchrome.runtime.onMessage.addListener((message, sender, sendResponse) => {\n  if (message.action === 'getData') {\n    \u002F\u002F 从存储中获取数据并返回\n    chrome.storage.local.get(['key']).then((result) => {\n      sendResponse({ data: result.key });\n    });\n    return true; \u002F\u002F 保持消息通道开放以支持异步响应\n  }\n});\n```\n\n### 内容脚本开发\n\n内容脚本在网页上下文中运行，可以访问和操作DOM，但与网页的JavaScript环境隔离。\n\n```javascript\n\u002F\u002F content-script.js\n\u002F\u002F 监听来自服务工作者的消息\nchrome.runtime.onMessage.addListener((message, sender, sendResponse) => {\n  if (message.action === 'pageLoaded') {\n    modifyPageContent();\n  }\n});\n\n\u002F\u002F 修改页面内容\nfunction modifyPageContent() {\n  \u002F\u002F 添加自定义样式类\n  document.body.classList.add('extension-modified');\n  \n  \u002F\u002F 查找特定元素并修改\n  const headings = document.querySelectorAll('h1, h2, h3');\n  headings.forEach(heading => {\n    heading.style.backgroundColor = '#f0f0f0';\n    heading.style.padding = '10px';\n  });\n  \n  \u002F\u002F 注入自定义按钮\n  const button = document.createElement('button');\n  button.textContent = '扩展功能';\n  button.addEventListener('click', handleButtonClick);\n  document.body.appendChild(button);\n}\n\nfunction handleButtonClick() {\n  \u002F\u002F 向服务工作者发送消息\n  chrome.runtime.sendMessage({ action: 'buttonClicked' }, (response) => {\n    console.log('收到响应:', response);\n  });\n}\n\n\u002F\u002F 监听DOM变化\nconst observer = new MutationObserver((mutations) => {\n  mutations.forEach((mutation) => {\n    if (mutation.addedNodes.length) {\n      \u002F\u002F 对新添加的节点进行处理\n      mutation.addedNodes.forEach((node) => {\n        if (node.nodeType === 1 && node.matches('.dynamic-content')) {\n          processDynamicContent(node);\n        }\n      });\n    }\n  });\n});\n\nobserver.observe(document.body, {\n  childList: true,\n  subtree: true\n});\n```\n\n### 弹出界面实现\n\n弹出界面是用户点击工具栏图标时显示的小窗口，提供快速访问扩展功能的界面。\n\n```html\n\u003C!-- popup.html -->\n\u003C!DOCTYPE html>\n\u003Chtml>\n\u003Chead>\n  \u003Cmeta charset=\"utf-8\">\n  \u003Cstyle>\n    body {\n      width: 300px;\n      padding: 15px;\n      font-family: Arial, sans-serif;\n    }\n    .header {\n      font-size: 16px;\n      font-weight: bold;\n      margin-bottom: 10px;\n    }\n    .button {\n      background-color: #4CAF50;\n      border: none;\n      color: white;\n      padding: 8px 16px;\n      text-align: center;\n      text-decoration: none;\n      display: inline-block;\n      font-size: 14px;\n      margin: 4px 2px;\n      cursor: pointer;\n      border-radius: 4px;\n    }\n    .status {\n      margin-top: 10px;\n      padding: 8px;\n      background-color: #f5f5f5;\n      border-radius: 4px;\n    }\n  \u003C\u002Fstyle>\n\u003C\u002Fhead>\n\u003Cbody>\n  \u003Cdiv class=\"header\">示例扩展\u003C\u002Fdiv>\n  \u003Cbutton id=\"actionBtn\" class=\"button\">执行操作\u003C\u002Fbutton>\n  \u003Cdiv id=\"status\" class=\"status\">就绪\u003C\u002Fdiv>\n\n  \u003Cscript src=\"popup.js\">\u003C\u002Fscript>\n\u003C\u002Fbody>\n\u003C\u002Fhtml>\n```\n\n```javascript\n\u002F\u002F popup.js\ndocument.addEventListener('DOMContentLoaded', () => {\n  const actionBtn = document.getElementById('actionBtn');\n  const statusDiv = document.getElementById('status');\n  \n  \u002F\u002F 从存储加载状态\n  chrome.storage.local.get(['extensionState']).then((result) => {\n    if (result.extensionState) {\n      statusDiv.textContent = `状态: ${result.extensionState}`;\n    }\n  });\n  \n  \u002F\u002F 按钮点击处理\n  actionBtn.addEventListener('click', () => {\n    statusDiv.textContent = '处理中...';\n    \n    \u002F\u002F 获取当前活动标签页\n    chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {\n      if (tabs[0]) {\n        \u002F\u002F 向内容脚本发送消息\n        chrome.tabs.sendMessage(tabs[0].id, { action: 'performAction' }, (response) => {\n          if (response && response.success) {\n            statusDiv.textContent = '操作完成';\n            \u002F\u002F 保存状态\n            chrome.storage.local.set({ extensionState: 'active' });\n          } else {\n            statusDiv.textContent = '操作失败';\n          }\n        });\n      }\n    });\n  });\n});\n```\n\n## 扩展程序API详解\n\n### 存储API\n\nChrome扩展程序提供chrome.storage API用于数据持久化，与localStorage相比，它支持异步操作、对象存储和更改监听。\n\n```javascript\n\u002F\u002F 存储数据示例\nasync function saveData() {\n  try {\n    await chrome.storage.local.set({\n      userPreferences: {\n        theme: 'dark',\n        notifications: true,\n        language: 'zh-CN'\n      },\n      lastUpdated: Date.now()\n    });\n    console.log('数据保存成功');\n  } catch (error) {\n    console.error('数据保存失败:', error);\n  }\n}\n\n\u002F\u002F 读取数据示例\nasync function loadData() {\n  try {\n    const result = await chrome.storage.local.get(['userPreferences', 'lastUpdated']);\n    return result;\n  } catch (error) {\n    console.error('数据读取失败:', error);\n    return null;\n  }\n}\n\n\u002F\u002F 监听存储变化\nchrome.storage.onChanged.addListener((changes, area) => {\n  if (area === 'local') {\n    for (const [key, { oldValue, newValue }] of Object.entries(changes)) {\n      console.log(`存储键 ${key} 已变更`, { 旧值: oldValue, 新值: newValue });\n    }\n  }\n});\n```\n\n### 标签页API\n\nchrome.tabs API允许扩展程序与浏览器标签页交互，包括创建、修改和查询标签页。\n\n```javascript\n\u002F\u002F 创建新标签页\nfunction createNewTab(url) {\n  chrome.tabs.create({ url, active: true });\n}\n\n\u002F\u002F 查询标签页\nasync function findTabs(pattern) {\n  const tabs = await chrome.tabs.query({ url: pattern });\n  return tabs;\n}\n\n\u002F\u002F 向特定标签页注入脚本\nasync function injectScript(tabId) {\n  try {\n    await chrome.scripting.executeScript({\n      target: { tabId },\n      files: ['content-script.js']\n    });\n    console.log('脚本注入成功');\n  } catch (error) {\n    console.error('脚本注入失败:', error);\n  }\n}\n\n\u002F\u002F 监听标签页激活事件\nchrome.tabs.onActivated.addListener((activeInfo) => {\n  console.log('激活的标签页ID:', activeInfo.tabId);\n});\n\n\u002F\u002F 监听标签页更新事件\nchrome.tabs.onUpdated.addListener((tabId, changeInfo, tab) => {\n  if (changeInfo.status === 'complete') {\n    console.log('标签页加载完成:', tab.url);\n  }\n});\n```\n\n### 运行时API\n\nchrome.runtime API提供扩展程序生命周期管理、消息传递和上下文信息。\n\n```javascript\n\u002F\u002F 获取扩展程序信息\nconst extensionInfo = chrome.runtime.getManifest();\nconsole.log('扩展程序名称:', extensionInfo.name);\nconsole.log('版本:', extensionInfo.version);\n\n\u002F\u002F 监听扩展程序安装和更新\nchrome.runtime.onInstalled.addListener((details) => {\n  if (details.reason === 'install') {\n    \u002F\u002F 显示欢迎页面\n    chrome.tabs.create({ url: 'welcome.html' });\n  }\n});\n\n\u002F\u002F 长连接消息传递\n\u002F\u002F 服务工作者端\nchrome.runtime.onConnect.addListener((port) => {\n  console.assert(port.name === 'content-script-connection');\n  \n  port.onMessage.addListener((msg) => {\n    if (msg.type === 'ping') {\n      port.postMessage({ type: 'pong', data: '服务工作者响应' });\n    }\n  });\n  \n  port.onDisconnect.addListener(() => {\n    console.log('连接已断开');\n  });\n});\n\n\u002F\u002F 内容脚本端\nconst port = chrome.runtime.connect({ name: 'content-script-connection' });\nport.postMessage({ type: 'ping' });\nport.onMessage.addListener((msg) => {\n  if (msg.type === 'pong') {\n    console.log('收到响应:', msg.data);\n  }\n});\n```\n\n## 权限系统与安全\n\n### 权限类型\n\nManifest V3的权限系统更加精细，分为权限（permissions）和主机权限（host_permissions）两类。\n\n```json\n{\n  \"permissions\": [\n    \"activeTab\",\n    \"storage\",\n    \"scripting\",\n    \"notifications\"\n  ],\n  \"host_permissions\": [\n    \"https:\u002F\u002Fapi.example.com\u002F*\",\n    \"https:\u002F\u002F*.website.com\u002F*\"\n  ]\n}\n```\n\n权限声明包括：\n- activeTab：在用户调用扩展程序时访问当前活动标签页\n- storage：使用chrome.storage API存储数据\n- scripting：通过程序方式注入和执行脚本\n- notifications：显示桌面通知\n\n### 内容安全策略\n\nManifest V3强化了内容安全策略（CSP），限制扩展程序中可执行的内容来源。\n\n```json\n{\n  \"content_security_policy\": {\n    \"extension_pages\": \"script-src 'self'; object-src 'self'\",\n    \"sandbox\": \"sandbox allow-scripts; script-src 'self' 'unsafe-eval' 'unsafe-inline'; object-src 'self'\"\n  }\n}\n```\n\n## 实际开发示例\n\n### 页面内容修改器扩展\n\n以下是一个完整的页面内容修改器扩展示例，展示Manifest V3扩展程序的基本结构和功能。\n\n```json\n\u002F\u002F manifest.json\n{\n  \"manifest_version\": 3,\n  \"name\": \"页面内容修改器\",\n  \"version\": \"1.0.0\",\n  \"description\": \"修改特定网页内容的示例扩展\",\n  \n  \"permissions\": [\n    \"activeTab\",\n    \"storage\",\n    \"scripting\"\n  ],\n  \n  \"host_permissions\": [\n    \"https:\u002F\u002F*.wikipedia.org\u002F*\"\n  ],\n  \n  \"background\": {\n    \"service_worker\": \"service-worker.js\"\n  },\n  \n  \"action\": {\n    \"default_popup\": \"popup.html\",\n    \"default_icon\": {\n      \"16\": \"icons\u002Ficon16.png\",\n      \"48\": \"icons\u002Ficon48.png\",\n      \"128\": \"icons\u002Ficon128.png\"\n    }\n  },\n  \n  \"content_scripts\": [\n    {\n      \"matches\": [\"https:\u002F\u002F*.wikipedia.org\u002F*\"],\n      \"js\": [\"content-script.js\"],\n      \"run_at\": \"document_idle\"\n    }\n  ],\n  \n  \"icons\": {\n    \"16\": \"icons\u002Ficon16.png\",\n    \"48\": \"icons\u002Ficon48.png\",\n    \"128\": \"icons\u002Ficon128.png\"\n  }\n}\n```\n\n```javascript\n\u002F\u002F service-worker.js\n\u002F\u002F 扩展安装处理\nchrome.runtime.onInstalled.addListener(() => {\n  \u002F\u002F 初始化默认设置\n  chrome.storage.local.set({\n    contentModifier: {\n      enabled: true,\n      highlightHeadings: true,\n      addBorder: false,\n      customText: '已通过扩展修改'\n    }\n  });\n});\n\n\u002F\u002F 处理来自弹出窗口的消息\nchrome.runtime.onMessage.addListener((message, sender, sendResponse) => {\n  if (message.action === 'toggleExtension') {\n    \u002F\u002F 切换扩展状态\n    chrome.storage.local.get(['contentModifier']).then((result) => {\n      const newState = !result.contentModifier.enabled;\n      chrome.storage.local.set({\n        contentModifier: { ...result.contentModifier, enabled: newState }\n      });\n      sendResponse({ enabled: newState });\n      \n      \u002F\u002F 通知所有标签页状态变化\n      chrome.tabs.query({ url: 'https:\u002F\u002F*.wikipedia.org\u002F*' }, (tabs) => {\n        tabs.forEach(tab => {\n          chrome.tabs.sendMessage(tab.id, {\n            action: 'extensionToggled',\n            enabled: newState\n          });\n        });\n      });\n    });\n    return true; \u002F\u002F 保持消息通道开放\n  }\n});\n```\n\n```javascript\n\u002F\u002F content-script.js\n\u002F\u002F 内容脚本主逻辑\nlet extensionEnabled = true;\n\n\u002F\u002F 从存储加载设置并应用\nchrome.storage.local.get(['contentModifier']).then((result) => {\n  if (result.contentModifier) {\n    extensionEnabled = result.contentModifier.enabled;\n    if (extensionEnabled) {\n      applyModifications(result.contentModifier);\n    }\n  }\n});\n\n\u002F\u002F 监听来自服务工作者的消息\nchrome.runtime.onMessage.addListener((message, sender, sendResponse) => {\n  if (message.action === 'extensionToggled') {\n    extensionEnabled = message.enabled;\n    if (extensionEnabled) {\n      chrome.storage.local.get(['contentModifier']).then((result) => {\n        applyModifications(result.contentModifier);\n      });\n    } else {\n      removeModifications();\n    }\n  }\n});\n\n\u002F\u002F 应用内容修改\nfunction applyModifications(settings) {\n  if (settings.highlightHeadings) {\n    highlightHeadings();\n  }\n  \n  if (settings.addBorder) {\n    addPageBorder();\n  }\n  \n  if (settings.customText) {\n    addCustomText(settings.customText);\n  }\n}\n\n\u002F\u002F 高亮标题\nfunction highlightHeadings() {\n  const headings = document.querySelectorAll('h1, h2, h3, h4, h5, h6');\n  headings.forEach(heading => {\n    heading.style.backgroundColor = '#fff3cd';\n    heading.style.padding = '8px';\n    heading.style.borderLeft = '4px solid #ffc107';\n  });\n}\n\n\u002F\u002F 添加页面边框\nfunction addPageBorder() {\n  document.body.style.border = '2px solid #4CAF50';\n  document.body.style.padding = '10px';\n}\n\n\u002F\u002F 添加自定义文本\nfunction addCustomText(text) {\n  const existingElement = document.getElementById('extension-custom-text');\n  if (existingElement) {\n    existingElement.remove();\n  }\n  \n  const customElement = document.createElement('div');\n  customElement.id = 'extension-custom-text';\n  customElement.textContent = text;\n  customElement.style.padding = '10px';\n  customElement.style.margin = '10px 0';\n  customElement.style.backgroundColor = '#e7f3ff';\n  customElement.style.border = '1px solid #b8daff';\n  customElement.style.borderRadius = '4px';\n  \n  const firstHeading = document.querySelector('h1');\n  if (firstHeading) {\n    firstHeading.parentNode.insertBefore(customElement, firstHeading.nextSibling);\n  } else {\n    document.body.insertBefore(customElement, document.body.firstChild);\n  }\n}\n\n\u002F\u002F 移除修改\nfunction removeModifications() {\n  \u002F\u002F 移除标题高亮\n  const headings = document.querySelectorAll('h1, h2, h3, h4, h5, h6');\n  headings.forEach(heading => {\n    heading.style.backgroundColor = '';\n    heading.style.padding = '';\n    heading.style.borderLeft = '';\n  });\n  \n  \u002F\u002F 移除页面边框\n  document.body.style.border = '';\n  document.body.style.padding = '';\n  \n  \u002F\u002F 移除自定义文本\n  const customElement = document.getElementById('extension-custom-text');\n  if (customElement) {\n    customElement.remove();\n  }\n}\n\n\u002F\u002F 监听DOM变化，对新添加的内容应用修改\nconst observer = new MutationObserver((mutations) => {\n  if (!extensionEnabled) return;\n  \n  mutations.forEach((mutation) => {\n    if (mutation.addedNodes.length) {\n      chrome.storage.local.get(['contentModifier']).then((result) => {\n        if (result.contentModifier && result.contentModifier.enabled) {\n          \u002F\u002F 对新添加的标题应用高亮\n          mutation.addedNodes.forEach((node) => {\n            if (node.nodeType === 1) {\n              const newHeadings = node.querySelectorAll && \n                node.querySelectorAll('h1, h2, h3, h4, h5, h6');\n              if (newHeadings) {\n                newHeadings.forEach(heading => {\n                  if (result.contentModifier.highlightHeadings) {\n                    heading.style.backgroundColor = '#fff3cd';\n                    heading.style.padding = '8px';\n                    heading.style.borderLeft = '4px solid #ffc107';\n                  }\n                });\n              }\n            }\n          });\n        }\n      });\n    }\n  });\n});\n\nobserver.observe(document.body, {\n  childList: true,\n  subtree: true\n});\n```\n\n```html\n\u003C!-- popup.html -->\n\u003C!DOCTYPE html>\n\u003Chtml>\n\u003Chead>\n  \u003Cmeta charset=\"utf-8\">\n  \u003Cstyle>\n    body {\n      width: 280px;\n      padding: 15px;\n      font-family: Arial, sans-serif;\n    }\n    .header {\n      font-size: 16px;\n      font-weight: bold;\n      margin-bottom: 15px;\n      color: #333;\n    }\n    .switch {\n      position: relative;\n      display: inline-block;\n      width: 50px;\n      height: 24px;\n      margin-right: 10px;\n    }\n    .switch input {\n      opacity: 0;\n      width: 0;\n      height: 0;\n    }\n    .slider {\n      position: absolute;\n      cursor: pointer;\n      top: 0;\n      left: 0;\n      right: 0;\n      bottom: 0;\n      background-color: #ccc;\n      transition: .4s;\n      border-radius: 24px;\n    }\n    .slider:before {\n      position: absolute;\n      content: \"\";\n      height: 16px;\n      width: 16px;\n      left: 4px;\n      bottom: 4px;\n      background-color: white;\n      transition: .4s;\n      border-radius: 50%;\n    }\n    input:checked + .slider {\n      background-color: #4CAF50;\n    }\n    input:checked + .slider:before {\n      transform: translateX(26px);\n    }\n    .option {\n      margin: 12px 0;\n      display: flex;\n      align-items: center;\n    }\n    .status {\n      margin-top: 15px;\n      padding: 10px;\n      border-radius: 4px;\n      text-align: center;\n      font-weight: bold;\n    }\n    .active {\n      background-color: #e7f7e7;\n      color: #2e7d32;\n    }\n    .inactive {\n      background-color: #f5f5f5;\n      color: #757575;\n    }\n  \u003C\u002Fstyle>\n\u003C\u002Fhead>\n\u003Cbody>\n  \u003Cdiv class=\"header\">页面内容修改器\u003C\u002Fdiv>\n  \n  \u003Cdiv class=\"option\">\n    \u003Clabel class=\"switch\">\n      \u003Cinput type=\"checkbox\" id=\"toggleExtension\">\n      \u003Cspan class=\"slider\">\u003C\u002Fspan>\n    \u003C\u002Flabel>\n    \u003Cspan>启用扩展\u003C\u002Fspan>\n  \u003C\u002Fdiv>\n  \n  \u003Cdiv class=\"option\">\n    \u003Clabel class=\"switch\">\n      \u003Cinput type=\"checkbox\" id=\"highlightHeadings\">\n      \u003Cspan class=\"slider\">\u003C\u002Fspan>\n    \u003C\u002Flabel>\n    \u003Cspan>高亮标题\u003C\u002Fspan>\n  \u003C\u002Fdiv>\n  \n  \u003Cdiv class=\"option\">\n    \u003Clabel class=\"switch\">\n      \u003Cinput type=\"checkbox\" id=\"addBorder\">\n      \u003Cspan class=\"slider\">\u003C\u002Fspan>\n    \u003C\u002Flabel>\n    \u003Cspan>添加页面边框\u003C\u002Fspan>\n  \u003C\u002Fdiv>\n  \n  \u003Cdiv id=\"status\" class=\"status inactive\">已禁用\u003C\u002Fdiv>\n\n  \u003Cscript src=\"popup.js\">\u003C\u002Fscript>\n\u003C\u002Fbody>\n\u003C\u002Fhtml>\n```\n\n```javascript\n\u002F\u002F popup.js\ndocument.addEventListener('DOMContentLoaded', () => {\n  const toggleExtension = document.getElementById('toggleExtension');\n  const highlightHeadings = document.getElementById('highlightHeadings');\n  const addBorder = document.getElementById('addBorder');\n  const statusDiv = document.getElementById('status');\n  \n  \u002F\u002F 从存储加载当前设置\n  chrome.storage.local.get(['contentModifier']).then((result) => {\n    if (result.contentModifier) {\n      const settings = result.contentModifier;\n      \n      toggleExtension.checked = settings.enabled;\n      highlightHeadings.checked = settings.highlightHeadings;\n      addBorder.checked = settings.addBorder;\n      \n      updateStatusDisplay(settings.enabled);\n    }\n  });\n  \n  \u002F\u002F 切换扩展状态\n  toggleExtension.addEventListener('change', () => {\n    chrome.runtime.sendMessage({ action: 'toggleExtension' }, (response) => {\n      if (response) {\n        updateStatusDisplay(response.enabled);\n        \n        \u002F\u002F 更新其他设置控件的状态\n        highlightHeadings.disabled = !response.enabled;\n        addBorder.disabled = !response.enabled;\n      }\n    });\n  });\n  \n  \u002F\u002F 更新高亮标题设置\n  highlightHeadings.addEventListener('change', () => {\n    chrome.storage.local.get(['contentModifier']).then((result) => {\n      const newSettings = {\n        ...result.contentModifier,\n        highlightHeadings: highlightHeadings.checked\n      };\n      chrome.storage.local.set({ contentModifier: newSettings });\n      \n      \u002F\u002F 通知内容脚本更新\n    });\n  });\n  \n  \u002F\u002F 更新边框设置\n  addBorder.addEventListener('change', () => {\n    chrome.storage.local.get(['contentModifier']).then((result) => {\n      const newSettings = {\n        ...result.contentModifier,\n        addBorder: addBorder.checked\n      };\n      chrome.storage.local.set({ contentModifier: newSettings });\n    });\n  });\n  \n  function updateStatusDisplay(enabled) {\n    if (enabled) {\n      statusDiv.textContent = '已启用';\n      statusDiv.className = 'status active';\n    } else {\n      statusDiv.textContent = '已禁用';\n      statusDiv.className = 'status inactive';\n    }\n  }\n});\n```\n\n## 调试与测试\n\n### 扩展程序加载\n\n在Chrome浏览器中调试扩展程序，首先需要将扩展程序加载到浏览器中：\n\n1. 打开Chrome浏览器，导航到`chrome:\u002F\u002Fextensions\u002F`\n2. 开启\"开发者模式\"\n3. 点击\"加载已解压的扩展程序\"，选择扩展程序目录\n4. 扩展程序将出现在扩展程序列表中，可以对其进行调试和测试\n\n### 服务工作者调试\n\n服务工作者可以通过以下步骤进行调试：\n\n1. 在`chrome:\u002F\u002Fextensions\u002F`页面，找到已加载的扩展程序\n2. 点击\"服务工作者\"链接，打开DevTools\n3. 在DevTools中设置断点、查看日志和监控网络请求\n\n### 内容脚本调试\n\n内容脚本在网页上下文中运行，可以通过以下方式调试：\n\n1. 在目标网页上打开DevTools\n2. 在\"源代码\"选项卡中，找到扩展程序的内容脚本\n3. 设置断点并调试，就像调试普通网页JavaScript一样\n\n### 弹出窗口调试\n\n右键点击扩展程序图标，选择\"检查弹出内容\"，即可打开专门针对弹出窗口的DevTools。\n\n## 打包与发布\n\n### 扩展程序打包\n\n完成开发和测试后，可以将扩展程序打包为CRX文件：\n\n1. 在`chrome:\u002F\u002Fextensions\u002F`页面，点击\"打包扩展程序\"\n2. 选择扩展程序根目录和私钥文件（如果是更新现有扩展程序）\n3. 点击\"打包扩展程序\"，生成CRX文件和PEM私钥文件\n\n### Chrome Web Store发布\n\n将扩展程序发布到Chrome Web Store需要：\n\n1. 创建开发者帐户并支付一次性注册费\n2. 在Chrome Web Store开发者仪表板中创建新项目\n3. 上传扩展程序ZIP文件（非CRX文件）\n4. 提供扩展程序描述、截图、图标等详细信息\n5. 提交审核，通过后即可公开发布\n\n## 性能优化\n\n### 服务工作者优化\n\n服务工作者应保持轻量级，避免长时间运行的任务：\n\n```javascript\n\u002F\u002F 良好实践：将长时间任务分解为小块\nasync function processLargeDataset(dataset) {\n  for (let i = 0; i \u003C dataset.length; i += 100) {\n    const chunk = dataset.slice(i, i + 100);\n    await processChunk(chunk);\n    \n    \u002F\u002F 定期检查是否需要继续执行\n    if (needsTermination()) {\n      break;\n    }\n  }\n}\n\n\u002F\u002F 使用Alarms API处理定期任务，而不是setInterval\nchrome.alarms.create('periodicTask', { periodInMinutes: 60 });\nchrome.alarms.onAlarm.addListener((alarm) => {\n  if (alarm.name === 'periodicTask') {\n    performPeriodicTask();\n  }\n});\n```\n\n### 消息传递优化\n\n优化扩展程序组件间的消息传递，减少不必要的通信：\n\n```javascript\n\u002F\u002F 批量处理消息，减少通信次数\nlet messageQueue = [];\nlet processing = false;\n\nasync function processMessageQueue() {\n  if (processing || messageQueue.length === 0) return;\n  \n  processing = true;\n  const messages = messageQueue.splice(0, messageQueue.length);\n  \n  try {\n    const results = await Promise.all(\n      messages.map(msg => \n        chrome.runtime.sendMessage(msg)\n      )\n    );\n    \u002F\u002F 处理结果\n  } catch (error) {\n    console.error('消息处理错误:', error);\n  } finally {\n    processing = false;\n    \u002F\u002F 检查是否有新消息到达\n    if (messageQueue.length > 0) {\n      processMessageQueue();\n    }\n  }\n}\n\nfunction queueMessage(message) {\n  messageQueue.push(message);\n  processMessageQueue();\n}\n```\n\n### 存储操作优化\n\n优化存储操作，减少读写次数：\n\n```javascript\n\u002F\u002F 批量存储操作\nconst storageCache = {};\nconst pendingWrites = new Set();\n\nfunction scheduleWrite(key, value) {\n  storageCache[key] = value;\n  pendingWrites.add(key);\n  \n  \u002F\u002F 延迟执行实际存储操作\n  clearTimeout(storageTimeout);\n  storageTimeout = setTimeout(flushStorage, 1000);\n}\n\nasync function flushStorage() {\n  const writes = {};\n  \n  pendingWrites.forEach(key => {\n    writes[key] = storageCache[key];\n  });\n  \n  if (Object.keys(writes).length > 0) {\n    await chrome.storage.local.set(writes);\n    pendingWrites.clear();\n  }\n}\n\n\u002F\u002F 读取时使用缓存\nasync function getCachedValue(key) {\n  if (storageCache[key] !== undefined) {\n    return storageCache[key];\n  }\n  \n  const result = await chrome.storage.local.get([key]);\n  storageCache[key] = result[key];\n  return result[key];\n}\n```\n\nChrome扩展程序Manifest V3通过引入服务工作者、声明式网络请求和远程代码限制等变化，显著提高了扩展程序的安全性、隐私性和性能。开发者需要理解这些变化并相应调整开发实践，以构建符合新标准的扩展程序。通过合理使用扩展程序API、优化组件间通信和实施性能最佳实践，可以创建出既功能强大又高效可靠的浏览器扩展程序。\n\n","\u002Ffrontend\u002Fbrowser_plugins"]