Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/google-cloud-platform/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Google chrome extension Chrome扩展,获取selectionText周围的文字_Google Chrome Extension - Fatal编程技术网

Google chrome extension Chrome扩展,获取selectionText周围的文字

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扩展,当用户选择一些文本时添加了一个菜单。 我想得到包含所选文本的完整句子,但我找不到方法

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事件和方法的环境中执行此操作。