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:
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>
The onselect event occurs after some text has been selected in an element. The onselect event is mostly used on <input type="text"> or <textarea> elements.
getSelection() method returns a Selection object representing the range of text selected by the user or the current position of the caret.
The selectionchange event of the Selection API is fired when the current Selection of a Document is changed. This event is not cancelable and does not bubble. The event can be handled by adding an event listener for selectionchange or using the onselectionchange event handler.
You can listen for changes in the text selection via the selectionchange
event. I believe that it's only available in WebKit browsers.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With