在gmail撰写邮件区域中获取选中/突出显示的文本html

get selected/highlighted text html in gmail compose mail area

本文关键字:显示 html 文本 获取 gmail 区域      更新时间:2023-09-26

我正在为Gmail设计一个chrome扩展。在这篇文章中,我想获得选中/突出显示的文本。我尝试了以下代码:

    if (!window.x) {
        x = {};
    }
    x.Selector = {};
    x.Selector.getSelected = function() {
        var t = '';
        if($('.compose-container').getSelection){
            t = $('.compose-container').getSelection();
            alert(t);
        } else if (window.getSelection) {
            t = window.getSelection();
        } else if (document.getSelection) {
            t = document.getSelection();
        } else if (document.selection) {
            t = document.selection.createRange().text;
        }
        return t;
    }

它不会在撰写邮件中给我选定的文本。请帮帮我。

您需要使用copy命令来实现这一点。

var copyText = document.execCommand('copy');  

基本上,它会复制浏览器中的任何文本选择。

您可以查看这个链接,了解它是如何被充分利用的

根据gRenzFries的回答,我的代码与他提供的链接相同。但在代码中添加了一点,将其粘贴到文本框中。

要复制的代码文本:

var emailLink = document.querySelector('.gmail_default');  
var range = document.createRange();  
range.selectNode(emailLink);  
window.getSelection().addRange(range);  
try {  
    // Now that we've selected the anchor text, execute the copy command  
    var successful = document.execCommand('copy', true);  
} catch(err) {
}

粘贴到文本框中的代码:

$('#text-to-display').val("");    //reset textbox value
$('#text-to-display').focus();    //set focus to textbox
document.execCommand("Paste");

此代码的工作方式与预期一致。