如何让事件监听器实时扩展chrome? [英] How to keep the eventlistener real time for chrome extensions?
问题描述
我怎样才能以它始终运行的方式来调用我的函数。
我想在用户双击时获得文本选择。所以我不知道如何附加一直保持的eventlistener。加载文档时不只是一次性函数。但更像是一个正在进行的eventlistener,只要该标签是开放的?
非常感谢!
为了实现您所描述的内容(并始终在每个选项卡上提供),您可以使用 内容脚本 ,并将其注入到每个页面中(请参阅下面的代码)。
如果您希望将其绑定到仅限特定标签,您可以使用 活动页面 ((即非持久背景页面),并为 chrome.tabs.onUpdated
事件和 以编程方式注入 内容scri每次在指定的选项卡中加载新页面时都是如此。
在上述内容脚本中,您可以将事件侦听器附加到 下面是一个扩展示例的源代码,它添加了每个标签所需的功能: content.js manifest.json How would I go about calling my function in a way that it is always running.
I want to get the text selection wherever the user double clicks. So I don't know how to attach the eventlistener that always stays on. not just a one time function when the document is loaded. but more like an ongoing eventlistener as long as the tab is open? Thanks you so much! In order to achieve what you describe (and to have it always available on every tab), you can use a content script and have it injected in every page (see code below). In the aforementioned content script, you can attach an event-listener to the Below is the source code of a sample extension that adds the desired "feature" to every tab: content.js manifest.json
这篇关于如何让事件监听器实时扩展chrome?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!文档
var listener = function(evt){
var selection = window.getSelection();
if(selection.rangeCount> 0){
var range = selection.getRangeAt(0);
var text = range.cloneContents()。textContent;
console.log(文本);
}
};
document.addEventListener('dblclick',listener);
{
manifest_version:2,
name:Test Extension,
version: 0.0,
offline_enabled:true,
content_scripts:[{
matches:[< all_urls>],
js :[content.js],
run_at:document_end,
all_frames:false
}]
}
If you want it to be bound to a specific tab only, you can utilize an event page (i.e. a non-persistent background page) and register a listener for the chrome.tabs.onUpdated
event and programmatically inject the content script every time a new page is loaded in the specified tab.document
itself to capture all events.
var listener = function(evt) {
var selection = window.getSelection();
if (selection.rangeCount > 0) {
var range = selection.getRangeAt(0);
var text = range.cloneContents().textContent;
console.log(text);
}
};
document.addEventListener('dblclick', listener);
{
"manifest_version": 2,
"name": "Test Extension",
"version": "0.0",
"offline_enabled": true,
"content_scripts": [{
"matches": ["<all_urls>"],
"js": ["content.js"],
"run_at": "document_end",
"all_frames": false
}]
}