get selected/highlighted text html in gmail compose mail area

时光怂恿深爱的人放手 提交于 2020-01-02 09:21:47

问题


I am designing an chrome extension for Gmail. In this I want to get selected/highlighted text. I tried following code:

    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;
    }

It is not giving me selected text in compose mail. Please help me out.


回答1:


You would need to use the copy command to achieve this.

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

Basically it will copy any text selection in the browser.

You can check out this link on how it was fully utilized




回答2:


As per gRenzFries answer, I code same as link provided by him. But slight addition in code to paste it in textbox.

Code to Copy text :

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) {
}

Code to paste it in textbox:

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

This code works just as expected.



来源:https://stackoverflow.com/questions/34525135/get-selected-highlighted-text-html-in-gmail-compose-mail-area

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!