Google chrome extension Chrome扩展,获取selectionText周围的文字
我创建了一个基本的Chrome扩展,当用户选择一些文本时添加了一个菜单。 我想得到包含所选文本的完整句子,但我找不到方法Google chrome extension Chrome扩展,获取selectionText周围的文字,google-chrome-extension,Google Chrome Extension,我创建了一个基本的Chrome扩展,当用户选择一些文本时添加了一个菜单。 我想得到包含所选文本的完整句子,但我找不到方法 chrome.contextMenus.create({ title: "Selected text: %s", contexts:["selection"], onclick: doSmth, }); function doSmth(info,tab) { console.log(info) } 输出: {可编辑:false,frameId:0,menu
chrome.contextMenus.create({
title: "Selected text: %s",
contexts:["selection"],
onclick: doSmth,
});
function doSmth(info,tab) {
console.log(info)
}
输出:
{可编辑:false,frameId:0,menuItemId:9,pageUrl:
"",
selectionText:“虹吸”}
我希望得到包含所选单词的完整句子,而不是“虹吸Nées”。有可能吗?我发现最简单的方法是直接从后台脚本运行代码注入: background.js
chrome.contextMenus.create({
title: 'Selected text: %s',
contexts: ['selection'],
onclick: doSmth,
});
function doSmth(info, tab) {
chrome.tabs.executeScript(tab.id, {
file: 'inject.js'
}, result => {
console.log(result[0]); // sentence
});
}
(function() {
const selection = window.getSelection();
const chunk = selection.baseNode.textContent.slice(selection.baseOffset, selection.extentOffset);
const re = new RegExp("(?:^|\\.\\s)((.(?!\\.\\s))*?)"+chunk+".*?\\.", 'g');
return selection.baseNode.textContent.match(re);
})();
inject.js
chrome.contextMenus.create({
title: 'Selected text: %s',
contexts: ['selection'],
onclick: doSmth,
});
function doSmth(info, tab) {
chrome.tabs.executeScript(tab.id, {
file: 'inject.js'
}, result => {
console.log(result[0]); // sentence
});
}
(function() {
const selection = window.getSelection();
const chunk = selection.baseNode.textContent.slice(selection.baseOffset, selection.extentOffset);
const re = new RegExp("(?:^|\\.\\s)((.(?!\\.\\s))*?)"+chunk+".*?\\.", 'g');
return selection.baseNode.textContent.match(re);
})();
它使用window.getSelection()
获取所选文本,然后执行正则表达式以获取句子 您必须在一个使用标准DOM事件和方法的环境中执行此操作。