Search code examples
javascriptgoogle-chrome-extensiondom-events

JavaScript text selection events


This is not just for Google Chrome extension but also for JavaScript

I am writing a Chrome extension in which when a text is highlighted and a context menu is shown I display my item in the context menu which when clicked should process the selected text.

After bringing up the context menu and selecting my option I get empty object with all values zeros and nulls..

So I want to implement some mechanism which will buffer the text selection as soon as the user releases the mouse after selecting the text so that an event can fire and if anything fires I can make a copy of the selected text in a global variable and can process later.

window.getSelected() is working fine when I tested with a separate testing code but while using with my extension where I bring up the context menu I could not get the actual selected text.

The selected text as I see in documentations would be of text and html.

Suggestions please...


Here I have pasted what I am doing. When I click save to word reminder I get an empty string:

enter image description here

and here is the rest of the code:

<script>
chrome.extension.onRequest.addListener(function(request, sender, sendResponse) {


    switch(request.message)
    {
        case 'getSelection':
            sendResponse({data: window.getSelection().toString()});
        break;
        
        case 'createMenu':
            seecon();
            break;
        
        default:
            sendResponse({data: 'Invalid arguments'});
        break;
    }
});

function conOnClick(info,tab)
{

/*
    chrome.extension.sendRequest(tab.id, {method: 'getSelection'}, function(response){
        alert(response.data);
    });
*/  
}


//function seecon()
{
var contexts = ["selection"];
for (var i = 0; i < contexts.length; i++) {
  var context = contexts[i];
  var title = "Save to Word Reminder";
  var id = chrome.contextMenus.create({"title": title, "contexts":[context],
                                       "onclick": conOnClick});
  
}

}



</script>

Solution

  • I would simply set a mouseUp event on the document, and then check if there is any selection (and if yes, whether the selection is different from the previous selection).