How to replace the highlighted text in text area to something of choice through context menu?
I am using Chrome APIs to manipulate the context menus. Since it is not easily runnable on SO, I have changed it to trigger on pressing Enter.
// context menu code
/*
chrome.contextMenus.create({
title: "tests",
contexts:["selection"],
onclick: scrap
});
*/
const scrap = () => {
text = window.getSelection().toString();
console.log(text);
}
document.getElementById('test').addEventListener("keypress", () => {
if (event.key === "Enter") {
event.preventDefault();
scrap();
}
});
<input type="text" id="test" name="test">
EDIT
how to get this working by selecting an option from context menu?
document.getElementById('test').addEventListener("keypress", () => {
if (event.key === "Enter") {
event.preventDefault();
scrap();
}
});
function scrap()
{
console.log("test");
var txtarea = document.getElementById("test");
var allText = txtarea.value;
console.log(allText);//works
var start = txtarea.selectionStart;
var finish = txtarea.selectionEnd;
var allText = txtarea.value;
var newText=allText.substring(0, start)+"mytextreplacemnt"+allText.substring(finish, allText.length);
txtarea.value=newText;
console.log(newText);
}
<input type="text" id="test" name="test">