javascript - Chrome 扩展 javascript,更改文本区域中选定的文本

标签 javascript html google-chrome google-chrome-extension

我正在编写一个 Chrome 扩展程序,但我不知道如何将文本区域内单击选定的文本更改为其他内容。

我一直在寻找一些答案,但所有这些答案都是针对我们知道文本区域 id 的情况,然后我们使用 getElementById 查找它,以便我们可以更改其内容。

我正在寻找适用于任何使用文本区域的网站的解决方案。这是我当前的代码:

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,
});

最佳答案

这是一个工作演示,不包括加密:

// 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>

关于javascript - Chrome 扩展 javascript,更改文本区域中选定的文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44336617/

相关文章:

javascript - 在子组件的状态之间共享父状态?

javascript - Angular : Return id From $http Inside Parent Function

html - 检查器窗口html中的::标记是什么意思?

google-chrome - tomcat 网络服务器重启后 Chrome cookies 不工作

javascript - Firefox Addons SDK - 如何从内容脚本访问简单存储?

html - 我的网站有一个小错误

html - 100vh 的主体尺寸不适用于响应式布局

javascript - 在 chrome.browserAction.onClicked 上调用内容脚本函数

google-chrome - 在 chrome 上禁用本地主机上的任何证书检查

javascript变量显示意外结果