问题
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 any thing 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>
回答1:
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).
回答2:
You can listen for changes in the text selection via the selectionchange
event. I believe that it's only available in WebKit browsers.
来源:https://stackoverflow.com/questions/9064363/javascript-text-selection-events