84669 人学习
152542 人学习
20005 人学习
5487 人学习
7821 人学习
359900 人学习
3350 人学习
180660 人学习
48569 人学习
18603 人学习
40936 人学习
1549 人学习
1183 人学习
32909 人学习
我正在编写一个 Chrome 扩展程序,并尝试在 popup.html 文件中单击按钮后立即在当前网页上覆盖 。 当我从 popup.html 中访问 document.body.insertBefore 方法时,它会覆盖弹出窗口上的 ,而不是当前网页。 我是否必须在background.html 和popup.html 之间使用消息传递才能访问网页的DOM?我想在 popup.html 中完成所有操作,并且如果可能的话也使用 jQuery。 2 0 0 P粉046878197 全部回复(2) 我来回复 关闭 P粉2960800762023-10-19 08:17:05 2 楼 使用编程注入来添加该 div 的扩展弹出脚本的一些示例。 清单V3 不要忘记在manifest.json中添加权限,请参阅其他答案以获取更多信息。 简单调用: (async () => { const [tab] = await chrome.tabs.query({active: true, currentWindow: true}); await chrome.scripting.executeScript({ target: {tabId: tab.id}, func: inContent1, }); })(); // executeScript runs this code inside the tab function inContent1() { const el = document.createElement('div'); el.style.cssText = 'position:fixed; top:0; left:0; right:0; background:red'; el.textContent = 'DIV'; document.body.appendChild(el); } 注意:在 Chrome 91 或更早版本中,func: 应为 function:。 使用参数调用并接收结果 需要 Chrome 92,因为它实现了 args。 示例1: res = await chrome.scripting.executeScript({ target: {tabId: tab.id}, func: (a, b) => { return [window[a], window[b]]; }, args: ['foo', 'bar'], }); 示例2: (async () => { const [tab] = await chrome.tabs.query({active: true, currentWindow: true}); let res; try { res = await chrome.scripting.executeScript({ target: {tabId: tab.id}, func: inContent2, args: [{ foo: 'bar' }], // arguments must be JSON-serializable }); } catch (e) { console.warn(e.message || e); return; } // res[0] contains results for the main page of the tab document.body.textContent = JSON.stringify(res[0].result); })(); // executeScript runs this code inside the tab function inContent2(params) { const el = document.createElement('div'); el.style.cssText = 'position:fixed; top:0; left:0; right:0; background:red'; el.textContent = params.foo; document.body.appendChild(el); return { success: true, html: document.body.innerHTML, }; } 清单V2 简单调用: // uses inContent1 from ManifestV3 example above chrome.tabs.executeScript({ code: `(${ inContent1 })()` }); 使用参数调用并接收结果: // uses inContent2 from ManifestV3 example above chrome.tabs.executeScript({ code: `(${ inContent2 })(${ JSON.stringify({ foo: 'bar' }) })` }, ([result] = []) => { if (!chrome.runtime.lastError) { console.log(result); // shown in devtools of the popup window } }); 此示例使用 inContent 函数的代码自动转换为字符串,这样做的好处是 IDE 可以应用语法突出显示和 linting。明显的缺点是浏览器会浪费时间来解析代码,但通常不到 1 毫秒,因此可以忽略不计。 点赞 +0 添加回复 关闭回复 P粉046878197 回复 P粉6004020852023-10-19 00:39:30 1 楼 问题:扩展页面(弹出窗口、选项、MV2 中的背景页面等)与网页分离,它们有自己的 DOM、document、window 和 chrome-extension:// URL。 请注意,Service Worker 根本没有任何 DOM/文档/窗口。 要检查扩展的每个上下文使用其自己的开发工具。 解决方案:使用内容脚本访问网络页面或与其内容交互。 内容脚本在网页中执行,而不是在扩展程序中执行。 内容脚本默认是隔离的,请参阅如何在页面上下文中运行代码(也称为主世界)。 不要在扩展程序页面中加载内容脚本。 方法1.声明式 manifest.json: "content_scripts": [{ "matches": ["*://*.example.com/*"], "js": ["contentScript.js"] }], 它将在页面加载时运行一次。之后,请使用消息传递。 警告!它不能发送 DOM 元素、Map、Set、ArrayBuffer、类、函数等。它只能发送与 JSON 兼容的简单对象和类型,因此您需要手动提取所需的数据并将其作为简单数组或对象传递。 方法 2. 程序化 ManifestV3: 在扩展脚本(如弹出窗口)可根据需要将内容脚本/函数注入选项卡。 此方法的结果是内容脚本中的最后一个表达式,因此可用于提取数据。数据必须与 JSON 兼容,请参阅上面的警告。 manifest.json 中所需的权限: “脚本” - 强制; "activeTab" - 理想场景,适合对用户操作的响应(通常是单击工具栏中的扩展图标)。安装扩展程序时不显示任何权限警告。 如果理想情况不可能,请将允许的站点添加到manifest.json 中的host_permissions: “*://*.example.com/” 以及您想要的任何其他网站。 "" 或 "*://*/" 这些会将您的扩展程序置于 Chrome 网上应用店中超慢审核队列中由于广泛的主机权限。 ManifestV2 与上述的差异: 使用chrome.tabs.executeScript。 在权限中指定网站。 点赞 +0 添加回复 关闭回复 P粉046878197 回复 热门专题 更多> Alat pertanyaan nama domain pendaftaran nohup和&的区别 c语言中+=的意思介绍 Apakah saiz kertas a5 热门文章 The German Government Has Transferred More Than 3,000 Bitcoin Since 11:11 AM UTC RBLK: The GambleFi Coin Primed to 100x in 2024 《活侠传》战术等级提升攻略 《原神》KFC联动活动介绍 涉及 1364 台发动机,日本日立造船公司子公司被曝燃油消耗率数据造假情况 热门教程 更多> 相关教程 热门推荐 最新课程 最新ThinkPHP 5.1全球首发视频教程(60天成就PHP大牛线上培训班课) 1386729 php入门教程之一周学会PHP 4193153 JAVA 初级入门视频教程 2293036 最新ThinkPHP 5.1全球首发视频教程(60天成就PHP大牛线上培训班课) 1386729 JAVA 初级入门视频教程 2293036 小甲鱼零基础入门学习Python视频教程 487557 Web前端开发极速入门 212808 零基础精通 PS 视频教程 827172 [Web front-end] Permulaan pantas Node.js 1895 Koleksi lengkap kursus timbunan penuh pembangunan web asing 1537 Gunakan GraphQL praktikal bahasa 1258 Master kipas 550W mempelajari JavaScript dari awal langkah demi langkah 367 Sarjana Python Mosh, seorang pemula dengan pengetahuan asas sifar boleh bermula dalam masa 6 jam 6767 最新下载 更多> 网站特效 网站源码 网站素材 前端模板 [butang borang] kod hubungan borang mesej perusahaan jQuery [Kesan khas pemain] Kesan main balik kotak muzik MP3 HTML5 [Navigasi menu] HTML5 kesan khas menu navigasi animasi zarah sejuk [butang borang] jQuery bentuk visual seret dan lepas kod penyuntingan [Kesan khas pemain] Kod pemain muzik Kugou tiruan VUE.JS [kesan khas html5] Permainan kotak menolak html5 klasik [Gambar kesan khas] menatal jQuery untuk menambah atau mengurangkan kesan imej [Kesan album foto] Kesan zum hover kulit album peribadi CSS3 [Templat Bootstrap] 有机果蔬供应商网页模板 Bootstrap5 [templat bahagian belakang] Bootstrap3多功能数据信息后台管理响应式网页模板-Novus [Templat Bootstrap] 房产资源服务平台网页模板 Bootstrap5 [Templat Bootstrap] 简约简历资料网页模板 Bootstrap4 [Templat Bootstrap] bootstrap响应式宽屏图书教育网站模板-DREAMLIFE [templat bahagian belakang] MAC风格响应式蓝色企业CMS后台管理系统模版 [templat bahagian belakang] 响应式渐变大气后台管理系统网站模板-usinessbox [Templat Bootstrap] 响应式蔬菜水果商店网站模板-Organio [PNG素材] 可爱的夏天元素矢量素材(EPS+PNG) [PNG素材] 四个红的的 2023 毕业徽章矢量素材(AI+EPS+PNG) [banner图] 唱歌的小鸟和装满花朵的推车设计春天banner矢量素材(AI+EPS) [PNG素材] 金色的毕业帽矢量素材(EPS+PNG) [PNG素材] 黑白风格的山脉图标矢量素材(EPS+PNG) [PNG素材] 不同颜色披风和不同姿势的超级英雄剪影矢量素材(EPS+PNG) [banner图] 扁平风格的植树节banner矢量素材(AI+EPS) [PNG素材] 九个漫画风格的爆炸聊天气泡矢量素材(EPS+PNG) [Templat bahagian hadapan] Templat Laman Web Syarikat Pembersihan dan Pembaikan Hiasan Rumah [Templat bahagian hadapan] Templat halaman panduan resume peribadi berwarna segar [Templat bahagian hadapan] Templat Web Resume Kerja Kreatif Pereka [Templat bahagian hadapan] Templat laman web syarikat pembinaan kejuruteraan moden [Templat bahagian hadapan] Templat HTML5 responsif untuk institusi perkhidmatan pendidikan [Templat bahagian hadapan] Templat laman web pusat membeli-belah kedai e-buku dalam talian [Templat bahagian hadapan] Teknologi IT menyelesaikan templat tapak web syarikat Internet [Templat bahagian hadapan] Templat laman web perkhidmatan perdagangan pertukaran asing gaya ungu
。 当我从 popup.html 中访问 document.body.insertBefore 方法时,它会覆盖弹出窗口上的 ,而不是当前网页。 我是否必须在background.html 和popup.html 之间使用消息传递才能访问网页的DOM?我想在 popup.html 中完成所有操作,并且如果可能的话也使用 jQuery。 2 0 0 P粉046878197 全部回复(2) 我来回复 关闭 P粉2960800762023-10-19 08:17:05 2 楼 使用编程注入来添加该 div 的扩展弹出脚本的一些示例。 清单V3 不要忘记在manifest.json中添加权限,请参阅其他答案以获取更多信息。 简单调用: (async () => { const [tab] = await chrome.tabs.query({active: true, currentWindow: true}); await chrome.scripting.executeScript({ target: {tabId: tab.id}, func: inContent1, }); })(); // executeScript runs this code inside the tab function inContent1() { const el = document.createElement('div'); el.style.cssText = 'position:fixed; top:0; left:0; right:0; background:red'; el.textContent = 'DIV'; document.body.appendChild(el); } 注意:在 Chrome 91 或更早版本中,func: 应为 function:。 使用参数调用并接收结果 需要 Chrome 92,因为它实现了 args。 示例1: res = await chrome.scripting.executeScript({ target: {tabId: tab.id}, func: (a, b) => { return [window[a], window[b]]; }, args: ['foo', 'bar'], }); 示例2: (async () => { const [tab] = await chrome.tabs.query({active: true, currentWindow: true}); let res; try { res = await chrome.scripting.executeScript({ target: {tabId: tab.id}, func: inContent2, args: [{ foo: 'bar' }], // arguments must be JSON-serializable }); } catch (e) { console.warn(e.message || e); return; } // res[0] contains results for the main page of the tab document.body.textContent = JSON.stringify(res[0].result); })(); // executeScript runs this code inside the tab function inContent2(params) { const el = document.createElement('div'); el.style.cssText = 'position:fixed; top:0; left:0; right:0; background:red'; el.textContent = params.foo; document.body.appendChild(el); return { success: true, html: document.body.innerHTML, }; } 清单V2 简单调用: // uses inContent1 from ManifestV3 example above chrome.tabs.executeScript({ code: `(${ inContent1 })()` }); 使用参数调用并接收结果: // uses inContent2 from ManifestV3 example above chrome.tabs.executeScript({ code: `(${ inContent2 })(${ JSON.stringify({ foo: 'bar' }) })` }, ([result] = []) => { if (!chrome.runtime.lastError) { console.log(result); // shown in devtools of the popup window } }); 此示例使用 inContent 函数的代码自动转换为字符串,这样做的好处是 IDE 可以应用语法突出显示和 linting。明显的缺点是浏览器会浪费时间来解析代码,但通常不到 1 毫秒,因此可以忽略不计。 点赞 +0 添加回复 关闭回复 P粉046878197 回复 P粉6004020852023-10-19 00:39:30 1 楼 问题:扩展页面(弹出窗口、选项、MV2 中的背景页面等)与网页分离,它们有自己的 DOM、document、window 和 chrome-extension:// URL。 请注意,Service Worker 根本没有任何 DOM/文档/窗口。 要检查扩展的每个上下文使用其自己的开发工具。 解决方案:使用内容脚本访问网络页面或与其内容交互。 内容脚本在网页中执行,而不是在扩展程序中执行。 内容脚本默认是隔离的,请参阅如何在页面上下文中运行代码(也称为主世界)。 不要在扩展程序页面中加载内容脚本。 方法1.声明式 manifest.json: "content_scripts": [{ "matches": ["*://*.example.com/*"], "js": ["contentScript.js"] }], 它将在页面加载时运行一次。之后,请使用消息传递。 警告!它不能发送 DOM 元素、Map、Set、ArrayBuffer、类、函数等。它只能发送与 JSON 兼容的简单对象和类型,因此您需要手动提取所需的数据并将其作为简单数组或对象传递。 方法 2. 程序化 ManifestV3: 在扩展脚本(如弹出窗口)可根据需要将内容脚本/函数注入选项卡。 此方法的结果是内容脚本中的最后一个表达式,因此可用于提取数据。数据必须与 JSON 兼容,请参阅上面的警告。 manifest.json 中所需的权限: “脚本” - 强制; "activeTab" - 理想场景,适合对用户操作的响应(通常是单击工具栏中的扩展图标)。安装扩展程序时不显示任何权限警告。 如果理想情况不可能,请将允许的站点添加到manifest.json 中的host_permissions: “*://*.example.com/” 以及您想要的任何其他网站。 "" 或 "*://*/" 这些会将您的扩展程序置于 Chrome 网上应用店中超慢审核队列中由于广泛的主机权限。 ManifestV2 与上述的差异: 使用chrome.tabs.executeScript。 在权限中指定网站。 点赞 +0 添加回复 关闭回复 P粉046878197 回复 热门专题 更多> Alat pertanyaan nama domain pendaftaran nohup和&的区别 c语言中+=的意思介绍 Apakah saiz kertas a5 热门文章 The German Government Has Transferred More Than 3,000 Bitcoin Since 11:11 AM UTC RBLK: The GambleFi Coin Primed to 100x in 2024 《活侠传》战术等级提升攻略 《原神》KFC联动活动介绍 涉及 1364 台发动机,日本日立造船公司子公司被曝燃油消耗率数据造假情况 热门教程 更多> 相关教程 热门推荐 最新课程 最新ThinkPHP 5.1全球首发视频教程(60天成就PHP大牛线上培训班课) 1386729 php入门教程之一周学会PHP 4193153 JAVA 初级入门视频教程 2293036 最新ThinkPHP 5.1全球首发视频教程(60天成就PHP大牛线上培训班课) 1386729 JAVA 初级入门视频教程 2293036 小甲鱼零基础入门学习Python视频教程 487557 Web前端开发极速入门 212808 零基础精通 PS 视频教程 827172 [Web front-end] Permulaan pantas Node.js 1895 Koleksi lengkap kursus timbunan penuh pembangunan web asing 1537 Gunakan GraphQL praktikal bahasa 1258 Master kipas 550W mempelajari JavaScript dari awal langkah demi langkah 367 Sarjana Python Mosh, seorang pemula dengan pengetahuan asas sifar boleh bermula dalam masa 6 jam 6767 最新下载 更多> 网站特效 网站源码 网站素材 前端模板 [butang borang] kod hubungan borang mesej perusahaan jQuery [Kesan khas pemain] Kesan main balik kotak muzik MP3 HTML5 [Navigasi menu] HTML5 kesan khas menu navigasi animasi zarah sejuk [butang borang] jQuery bentuk visual seret dan lepas kod penyuntingan [Kesan khas pemain] Kod pemain muzik Kugou tiruan VUE.JS [kesan khas html5] Permainan kotak menolak html5 klasik [Gambar kesan khas] menatal jQuery untuk menambah atau mengurangkan kesan imej [Kesan album foto] Kesan zum hover kulit album peribadi CSS3 [Templat Bootstrap] 有机果蔬供应商网页模板 Bootstrap5 [templat bahagian belakang] Bootstrap3多功能数据信息后台管理响应式网页模板-Novus [Templat Bootstrap] 房产资源服务平台网页模板 Bootstrap5 [Templat Bootstrap] 简约简历资料网页模板 Bootstrap4 [Templat Bootstrap] bootstrap响应式宽屏图书教育网站模板-DREAMLIFE [templat bahagian belakang] MAC风格响应式蓝色企业CMS后台管理系统模版 [templat bahagian belakang] 响应式渐变大气后台管理系统网站模板-usinessbox [Templat Bootstrap] 响应式蔬菜水果商店网站模板-Organio [PNG素材] 可爱的夏天元素矢量素材(EPS+PNG) [PNG素材] 四个红的的 2023 毕业徽章矢量素材(AI+EPS+PNG) [banner图] 唱歌的小鸟和装满花朵的推车设计春天banner矢量素材(AI+EPS) [PNG素材] 金色的毕业帽矢量素材(EPS+PNG) [PNG素材] 黑白风格的山脉图标矢量素材(EPS+PNG) [PNG素材] 不同颜色披风和不同姿势的超级英雄剪影矢量素材(EPS+PNG) [banner图] 扁平风格的植树节banner矢量素材(AI+EPS) [PNG素材] 九个漫画风格的爆炸聊天气泡矢量素材(EPS+PNG) [Templat bahagian hadapan] Templat Laman Web Syarikat Pembersihan dan Pembaikan Hiasan Rumah [Templat bahagian hadapan] Templat halaman panduan resume peribadi berwarna segar [Templat bahagian hadapan] Templat Web Resume Kerja Kreatif Pereka [Templat bahagian hadapan] Templat laman web syarikat pembinaan kejuruteraan moden [Templat bahagian hadapan] Templat HTML5 responsif untuk institusi perkhidmatan pendidikan [Templat bahagian hadapan] Templat laman web pusat membeli-belah kedai e-buku dalam talian [Templat bahagian hadapan] Teknologi IT menyelesaikan templat tapak web syarikat Internet [Templat bahagian hadapan] Templat laman web perkhidmatan perdagangan pertukaran asing gaya ungu
当我从 popup.html 中访问 document.body.insertBefore 方法时,它会覆盖弹出窗口上的 ,而不是当前网页。 我是否必须在background.html 和popup.html 之间使用消息传递才能访问网页的DOM?我想在 popup.html 中完成所有操作,并且如果可能的话也使用 jQuery。 2 0 0 P粉046878197 全部回复(2) 我来回复 关闭 P粉2960800762023-10-19 08:17:05 2 楼 使用编程注入来添加该 div 的扩展弹出脚本的一些示例。 清单V3 不要忘记在manifest.json中添加权限,请参阅其他答案以获取更多信息。 简单调用: (async () => { const [tab] = await chrome.tabs.query({active: true, currentWindow: true}); await chrome.scripting.executeScript({ target: {tabId: tab.id}, func: inContent1, }); })(); // executeScript runs this code inside the tab function inContent1() { const el = document.createElement('div'); el.style.cssText = 'position:fixed; top:0; left:0; right:0; background:red'; el.textContent = 'DIV'; document.body.appendChild(el); } 注意:在 Chrome 91 或更早版本中,func: 应为 function:。 使用参数调用并接收结果 需要 Chrome 92,因为它实现了 args。 示例1: res = await chrome.scripting.executeScript({ target: {tabId: tab.id}, func: (a, b) => { return [window[a], window[b]]; }, args: ['foo', 'bar'], }); 示例2: (async () => { const [tab] = await chrome.tabs.query({active: true, currentWindow: true}); let res; try { res = await chrome.scripting.executeScript({ target: {tabId: tab.id}, func: inContent2, args: [{ foo: 'bar' }], // arguments must be JSON-serializable }); } catch (e) { console.warn(e.message || e); return; } // res[0] contains results for the main page of the tab document.body.textContent = JSON.stringify(res[0].result); })(); // executeScript runs this code inside the tab function inContent2(params) { const el = document.createElement('div'); el.style.cssText = 'position:fixed; top:0; left:0; right:0; background:red'; el.textContent = params.foo; document.body.appendChild(el); return { success: true, html: document.body.innerHTML, }; } 清单V2 简单调用: // uses inContent1 from ManifestV3 example above chrome.tabs.executeScript({ code: `(${ inContent1 })()` }); 使用参数调用并接收结果: // uses inContent2 from ManifestV3 example above chrome.tabs.executeScript({ code: `(${ inContent2 })(${ JSON.stringify({ foo: 'bar' }) })` }, ([result] = []) => { if (!chrome.runtime.lastError) { console.log(result); // shown in devtools of the popup window } }); 此示例使用 inContent 函数的代码自动转换为字符串,这样做的好处是 IDE 可以应用语法突出显示和 linting。明显的缺点是浏览器会浪费时间来解析代码,但通常不到 1 毫秒,因此可以忽略不计。 点赞 +0 添加回复 关闭回复 P粉046878197 回复 P粉6004020852023-10-19 00:39:30 1 楼 问题:扩展页面(弹出窗口、选项、MV2 中的背景页面等)与网页分离,它们有自己的 DOM、document、window 和 chrome-extension:// URL。 请注意,Service Worker 根本没有任何 DOM/文档/窗口。 要检查扩展的每个上下文使用其自己的开发工具。 解决方案:使用内容脚本访问网络页面或与其内容交互。 内容脚本在网页中执行,而不是在扩展程序中执行。 内容脚本默认是隔离的,请参阅如何在页面上下文中运行代码(也称为主世界)。 不要在扩展程序页面中加载内容脚本。 方法1.声明式 manifest.json: "content_scripts": [{ "matches": ["*://*.example.com/*"], "js": ["contentScript.js"] }], 它将在页面加载时运行一次。之后,请使用消息传递。 警告!它不能发送 DOM 元素、Map、Set、ArrayBuffer、类、函数等。它只能发送与 JSON 兼容的简单对象和类型,因此您需要手动提取所需的数据并将其作为简单数组或对象传递。 方法 2. 程序化 ManifestV3: 在扩展脚本(如弹出窗口)可根据需要将内容脚本/函数注入选项卡。 此方法的结果是内容脚本中的最后一个表达式,因此可用于提取数据。数据必须与 JSON 兼容,请参阅上面的警告。 manifest.json 中所需的权限: “脚本” - 强制; "activeTab" - 理想场景,适合对用户操作的响应(通常是单击工具栏中的扩展图标)。安装扩展程序时不显示任何权限警告。 如果理想情况不可能,请将允许的站点添加到manifest.json 中的host_permissions: “*://*.example.com/” 以及您想要的任何其他网站。 "" 或 "*://*/" 这些会将您的扩展程序置于 Chrome 网上应用店中超慢审核队列中由于广泛的主机权限。 ManifestV2 与上述的差异: 使用chrome.tabs.executeScript。 在权限中指定网站。 点赞 +0 添加回复 关闭回复 P粉046878197 回复
document.body.insertBefore
,而不是当前网页。 我是否必须在background.html 和popup.html 之间使用消息传递才能访问网页的DOM?我想在 popup.html 中完成所有操作,并且如果可能的话也使用 jQuery。 2 0 0 P粉046878197 全部回复(2) 我来回复 关闭 P粉2960800762023-10-19 08:17:05 2 楼 使用编程注入来添加该 div 的扩展弹出脚本的一些示例。 清单V3 不要忘记在manifest.json中添加权限,请参阅其他答案以获取更多信息。 简单调用: (async () => { const [tab] = await chrome.tabs.query({active: true, currentWindow: true}); await chrome.scripting.executeScript({ target: {tabId: tab.id}, func: inContent1, }); })(); // executeScript runs this code inside the tab function inContent1() { const el = document.createElement('div'); el.style.cssText = 'position:fixed; top:0; left:0; right:0; background:red'; el.textContent = 'DIV'; document.body.appendChild(el); } 注意:在 Chrome 91 或更早版本中,func: 应为 function:。 使用参数调用并接收结果 需要 Chrome 92,因为它实现了 args。 示例1: res = await chrome.scripting.executeScript({ target: {tabId: tab.id}, func: (a, b) => { return [window[a], window[b]]; }, args: ['foo', 'bar'], }); 示例2: (async () => { const [tab] = await chrome.tabs.query({active: true, currentWindow: true}); let res; try { res = await chrome.scripting.executeScript({ target: {tabId: tab.id}, func: inContent2, args: [{ foo: 'bar' }], // arguments must be JSON-serializable }); } catch (e) { console.warn(e.message || e); return; } // res[0] contains results for the main page of the tab document.body.textContent = JSON.stringify(res[0].result); })(); // executeScript runs this code inside the tab function inContent2(params) { const el = document.createElement('div'); el.style.cssText = 'position:fixed; top:0; left:0; right:0; background:red'; el.textContent = params.foo; document.body.appendChild(el); return { success: true, html: document.body.innerHTML, }; } 清单V2 简单调用: // uses inContent1 from ManifestV3 example above chrome.tabs.executeScript({ code: `(${ inContent1 })()` }); 使用参数调用并接收结果: // uses inContent2 from ManifestV3 example above chrome.tabs.executeScript({ code: `(${ inContent2 })(${ JSON.stringify({ foo: 'bar' }) })` }, ([result] = []) => { if (!chrome.runtime.lastError) { console.log(result); // shown in devtools of the popup window } }); 此示例使用 inContent 函数的代码自动转换为字符串,这样做的好处是 IDE 可以应用语法突出显示和 linting。明显的缺点是浏览器会浪费时间来解析代码,但通常不到 1 毫秒,因此可以忽略不计。 点赞 +0 添加回复 关闭回复 P粉046878197 回复 P粉6004020852023-10-19 00:39:30 1 楼 问题:扩展页面(弹出窗口、选项、MV2 中的背景页面等)与网页分离,它们有自己的 DOM、document、window 和 chrome-extension:// URL。 请注意,Service Worker 根本没有任何 DOM/文档/窗口。 要检查扩展的每个上下文使用其自己的开发工具。 解决方案:使用内容脚本访问网络页面或与其内容交互。 内容脚本在网页中执行,而不是在扩展程序中执行。 内容脚本默认是隔离的,请参阅如何在页面上下文中运行代码(也称为主世界)。 不要在扩展程序页面中加载内容脚本。 方法1.声明式 manifest.json: "content_scripts": [{ "matches": ["*://*.example.com/*"], "js": ["contentScript.js"] }], 它将在页面加载时运行一次。之后,请使用消息传递。 警告!它不能发送 DOM 元素、Map、Set、ArrayBuffer、类、函数等。它只能发送与 JSON 兼容的简单对象和类型,因此您需要手动提取所需的数据并将其作为简单数组或对象传递。 方法 2. 程序化 ManifestV3: 在扩展脚本(如弹出窗口)可根据需要将内容脚本/函数注入选项卡。 此方法的结果是内容脚本中的最后一个表达式,因此可用于提取数据。数据必须与 JSON 兼容,请参阅上面的警告。 manifest.json 中所需的权限: “脚本” - 强制; "activeTab" - 理想场景,适合对用户操作的响应(通常是单击工具栏中的扩展图标)。安装扩展程序时不显示任何权限警告。 如果理想情况不可能,请将允许的站点添加到manifest.json 中的host_permissions: “*://*.example.com/” 以及您想要的任何其他网站。 "" 或 "*://*/" 这些会将您的扩展程序置于 Chrome 网上应用店中超慢审核队列中由于广泛的主机权限。 ManifestV2 与上述的差异: 使用chrome.tabs.executeScript。 在权限中指定网站。 点赞 +0 添加回复 关闭回复 P粉046878197 回复
我是否必须在background.html 和popup.html 之间使用消息传递才能访问网页的DOM?我想在 popup.html 中完成所有操作,并且如果可能的话也使用 jQuery。
使用编程注入来添加该 div 的扩展弹出脚本的一些示例。
不要忘记在manifest.json中添加权限,请参阅其他答案以获取更多信息。
简单调用:
(async () => { const [tab] = await chrome.tabs.query({active: true, currentWindow: true}); await chrome.scripting.executeScript({ target: {tabId: tab.id}, func: inContent1, }); })(); // executeScript runs this code inside the tab function inContent1() { const el = document.createElement('div'); el.style.cssText = 'position:fixed; top:0; left:0; right:0; background:red'; el.textContent = 'DIV'; document.body.appendChild(el); }
注意:在 Chrome 91 或更早版本中,func: 应为 function:。
func:
function:
使用参数调用并接收结果
需要 Chrome 92,因为它实现了 args。
args
示例1:
res = await chrome.scripting.executeScript({ target: {tabId: tab.id}, func: (a, b) => { return [window[a], window[b]]; }, args: ['foo', 'bar'], });
示例2:
(async () => { const [tab] = await chrome.tabs.query({active: true, currentWindow: true}); let res; try { res = await chrome.scripting.executeScript({ target: {tabId: tab.id}, func: inContent2, args: [{ foo: 'bar' }], // arguments must be JSON-serializable }); } catch (e) { console.warn(e.message || e); return; } // res[0] contains results for the main page of the tab document.body.textContent = JSON.stringify(res[0].result); })(); // executeScript runs this code inside the tab function inContent2(params) { const el = document.createElement('div'); el.style.cssText = 'position:fixed; top:0; left:0; right:0; background:red'; el.textContent = params.foo; document.body.appendChild(el); return { success: true, html: document.body.innerHTML, }; }
// uses inContent1 from ManifestV3 example above chrome.tabs.executeScript({ code: `(${ inContent1 })()` });
使用参数调用并接收结果:
// uses inContent2 from ManifestV3 example above chrome.tabs.executeScript({ code: `(${ inContent2 })(${ JSON.stringify({ foo: 'bar' }) })` }, ([result] = []) => { if (!chrome.runtime.lastError) { console.log(result); // shown in devtools of the popup window } });
此示例使用 inContent 函数的代码自动转换为字符串,这样做的好处是 IDE 可以应用语法突出显示和 linting。明显的缺点是浏览器会浪费时间来解析代码,但通常不到 1 毫秒,因此可以忽略不计。
inContent
问题:扩展页面(弹出窗口、选项、MV2 中的背景页面等)与网页分离,它们有自己的 DOM、document、window 和 chrome-extension:// URL。
document
chrome-extension://
解决方案:使用内容脚本访问网络页面或与其内容交互。
manifest.json:
"content_scripts": [{ "matches": ["*://*.example.com/*"], "js": ["contentScript.js"] }],
它将在页面加载时运行一次。之后,请使用消息传递。
警告!它不能发送 DOM 元素、Map、Set、ArrayBuffer、类、函数等。它只能发送与 JSON 兼容的简单对象和类型,因此您需要手动提取所需的数据并将其作为简单数组或对象传递。
ManifestV3:
在扩展脚本(如弹出窗口)可根据需要将内容脚本/函数注入选项卡。
此方法的结果是内容脚本中的最后一个表达式,因此可用于提取数据。数据必须与 JSON 兼容,请参阅上面的警告。
manifest.json 中所需的权限:
权限
“脚本”
"activeTab"
如果理想情况不可能,请将允许的站点添加到manifest.json 中的host_permissions:
host_permissions
“*://*.example.com/” 以及您想要的任何其他网站。
“*://*.example.com/”
"" 或 "*://*/" 这些会将您的扩展程序置于 Chrome 网上应用店中超慢审核队列中由于广泛的主机权限。
""
"*://*/"
ManifestV2 与上述的差异:
使用编程注入来添加该 div 的扩展弹出脚本的一些示例。
清单V3
不要忘记在manifest.json中添加权限,请参阅其他答案以获取更多信息。
简单调用:
注意:在 Chrome 91 或更早版本中,
func:
应为function:
。使用参数调用并接收结果
需要 Chrome 92,因为它实现了
args
。示例1:
示例2:
清单V2
简单调用:
使用参数调用并接收结果:
此示例使用
inContent
函数的代码自动转换为字符串,这样做的好处是 IDE 可以应用语法突出显示和 linting。明显的缺点是浏览器会浪费时间来解析代码,但通常不到 1 毫秒,因此可以忽略不计。问题:扩展页面(弹出窗口、选项、MV2 中的背景页面等)与网页分离,它们有自己的 DOM、
document
、window 和chrome-extension://
URL。解决方案:使用内容脚本访问网络页面或与其内容交互。
方法1.声明式
manifest.json:
它将在页面加载时运行一次。之后,请使用消息传递。
警告!它不能发送 DOM 元素、Map、Set、ArrayBuffer、类、函数等。它只能发送与 JSON 兼容的简单对象和类型,因此您需要手动提取所需的数据并将其作为简单数组或对象传递。
方法 2. 程序化
ManifestV3:
在扩展脚本(如弹出窗口)可根据需要将内容脚本/函数注入选项卡。
此方法的结果是内容脚本中的最后一个表达式,因此可用于提取数据。数据必须与 JSON 兼容,请参阅上面的警告。
manifest.json 中所需的
权限
:“脚本”
- 强制;"activeTab"
- 理想场景,适合对用户操作的响应(通常是单击工具栏中的扩展图标)。安装扩展程序时不显示任何权限警告。如果理想情况不可能,请将允许的站点添加到manifest.json 中的
host_permissions
:“*://*.example.com/”
以及您想要的任何其他网站。""
或"*://*/"
这些会将您的扩展程序置于 Chrome 网上应用店中超慢审核队列中由于广泛的主机权限。ManifestV2 与上述的差异:
权限
中指定网站。