如何创建一个“;表单弹出框“;在chrome中右键单击时位于突出显示的单词上方

How to create a "Form pop up box" above a highlighted word when rightclicked in chrome?

本文关键字:单击 右键 显示 单词 chrome 于突出 创建 何创建 一个 表单      更新时间:2023-09-26

我在开始创建chrome浏览器扩展时遇到了很多麻烦,如果用户突出显示一个单词,就会出现一个表单框,其中包含突出显示的单词和用户可以添加到其中的任何其他信息。该图像是我试图创建的东西的模型。我一直在学习chrome开发人员扩展教程,但我不确定如何将其应用于此。(此框的目的是稍后将其推送到数据库中)。浏览器扩展框的原型图像

要实现这一点,您需要做以下事情:

  1. 侦听右键单击事件。看看ContentScripts和Click事件,您可以使用以下代码来侦听右键单击事件。

    document.addEventListener("click", function(e) {
        if(e.button === 2) {
            // right mouse button
        }
    }, false);
    
  2. 获取突出显示的单词。你可以使用window.getSelection().toString()来获得它。

  3. 创建一个弹出框。在内容脚本中,您可以直接操作当前网页中的DOM,只需调用Document.createElementNode.appendChild即可创建和注入元素。

您需要创建一个包含以下内容的内容脚本:

function getSelectedText() {
    var text = "";
    if (typeof window.getSelection != "undefined") {
        text = window.getSelection().toString();
    } else if (typeof document.selection != "undefined" && document.selection.type == "Text") {
        text = document.selection.createRange().text;
    }
    return text;
}
document.addEventListener('mouseup', function(e) {
    var selectedText = getSelectedText();
    if (selectedText) {
        alert("Selected text:  " + selectedText);
    }
}, false);