我正在为Chrome写一个扩展程序,但我无法弄清楚如何将textarea中的所选文本更改为其他内容。
我正在寻找一些答案,但所有这些都是针对我们知道textarea的id的情况,然后我们使用getElementById查找它,以便我们可以更改其内容。
我正在寻找适用于任何使用textareas的网站的解决方案。这是我目前的代码:
function encrypt(info,tab) {
cryptoProperties = sjcl.encrypt("password", info.selectionText);
encoded_cryptoProperties = window.btoa("abcd");
}
chrome.contextMenus.create({
title: "encrypt: %s",
contexts:["selection"],
onclick: encrypt,
});
答案 0 :(得分:2)
这是一个工作演示,不包括加密:
// this will replace selected text immediately.
// A more user-friendly approach would be to process selected text here
// and then actually replace it after some sort of user-confirmation
document.addEventListener('mouseup', (event) => {
let element = document.activeElement;
if (element instanceof HTMLTextAreaElement) {
let {selectionStart, selectionEnd} = element;
// nothing is selected
if (selectionStart === selectionEnd) return;
let string = element.value;
let prefix = string.substring(0, selectionStart);
let infix = string.substring(selectionStart, selectionEnd);
let postfix = string.substring(selectionEnd);
element.value = prefix + 'REPLACED TEXT' + postfix;
}
});

<textarea cols="80" rows="10">Highlight me!
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
</textarea>
&#13;