简体   繁体   English

如何从Chrome扩展上下文在页面上运行脚本?

[英]How to run script on page from chrome extension context?

I want to know how I can be disabling the Event Listener "copy" 我想知道如何禁用事件监听器“复制”

I think it's something like this: 我认为是这样的:

.js file: .js文件:

let btn = document.getElementById('btn');

document.body.addEventListener('click', function(e) {
  if (e.target.id === 'btn') {
    e.stopPropagation();
  }
}, {
  capture: false
});

Thanks in advance! 提前致谢!

manifest.json: manifest.json:

{
  "name": "Test",
  "version": "1.0",
  "description": "Just testing!",
  "manifest_version": 2,
  "icons": {
    "48": "images/icon_48.png",
    "128": "images/icon_128.png"
  },
  "browser_action": {
    "default_icon": "images/icon_16.png",
    "default_popup": "popup.html"
  }
}

To access the web page you need a content script because the popup is a separate page with its own DOM, document , window , URL, everything. 要访问该网页,您需要一个内容脚本,因为弹出窗口是一个单独的页面,具有自己的DOM, documentwindow ,URL和所有内容。

You also need to intercept the copy event as seen in devtools' event listeners panel: 您还需要拦截copy事件,如devtools的事件侦听器面板中所示:

图片

manifest.json should have the following: manifest.json应该具有以下内容:

"content_scripts": [{
  "matches": ["https://moller.jusbrasil.com.br/*"],
  "js": ["content.js"],
  "run_at": "document_start"
}]

content.js: content.js:

window.addEventListener('copy', e => e.stopImmediatePropagation(), true);

Let's break it down: 让我们分解一下:

  1. the content script runs at document_start before any page script 内容脚本在任何页面脚本之前在document_start运行
  2. addEventListener's third parameter being true means our listener is invoked in the capturing phase of the event dispatch process - before any other standard bubbling phase listener addEventListener的第三个参数为true意味着在事件分发过程的捕获阶段中调用我们的侦听器-在任何其他标准冒泡阶段侦听器之前
  3. window is the first event target in the capturing phase window是捕获阶段的第一个事件目标
  4. stopImmediatePropagation() is used because we need both to stop the subsequent bubbling of the event and prevent any other listeners attached by the page script from seeing the event 使用stopImmediatePropagation()是因为我们既需要停止随后的事件冒泡,又需要阻止页面脚本附加的任何其他侦听器看到该事件

So the end result is that our listener is guaranteed to be invoked before the page listeners. 因此,最终结果是可以确保在页面侦听器之前调用我们的侦听器。

PS As you can see there's no need for the browser_action popup for this task. PS如您所见,此任务无需使用browser_action弹出窗口。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM