【问题标题】:Chrome extension javascript, change selected text in textareaChrome扩展javascript,更改textarea中的选定文本
【发布时间】:2017-11-04 07:39:15
【问题描述】:

我正在为 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,
});

【问题讨论】:

  • 除非我遗漏了什么,<textarea> 已经是一个可编辑的元素。为什么你认为你需要一个扩展来改变选定的文本?只需使用剪贴板粘贴和替换选定的文本...
  • 我想选择文本,点击加密,然后交换它。
  • 如何加密?您是否在某处存储了预设密钥?很高兴在您的问题中提及这一点,但听起来这已经太宽泛了。
  • 它甚至相关吗?我正在使用 sjcl 库。我已经对所选文本进行了加密,只是不知道如何交换它。
  • 是的,它是相关的,因为在不分享您目前拥有的现有代码的情况下,听起来您是在要求 stackoverflow 免费为您编写一个项目。

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


【解决方案1】:

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

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

【讨论】:

  • document.addEventListener 似乎不起作用,即使我只是放在那里只有警报(“警报”)。有什么想法吗?
  • 您必须获取上下文菜单所在选项卡的window 对象,然后执行tabWindow.document.addEventListener(...),但这超出了本问题的范围。
猜你喜欢
  • 1970-01-01
  • 2023-03-26
  • 2013-10-10
  • 1970-01-01
  • 2014-12-08
  • 1970-01-01
  • 2017-04-06
  • 2014-11-20
  • 2021-10-03
相关资源
最近更新 更多