【问题标题】:How to insert text into selected textbox in JavaScript without ID?如何在没有 ID 的 JavaScript 中将文本插入选定的文本框?
【发布时间】:2017-05-14 16:10:04
【问题描述】:

上下文:

  1. 使用 JavaScript 编写谷歌浏览器扩展
  2. 使用上下文菜单库
  3. 用户应该能够右键单击文本框,选择 chrome 扩展,选择“插入文本”,然后该文本将插入到选定的文本框中。
  4. 我使用的是纯 javascript,请不要使用 jquery 或 AJAX。
  5. 我无法编辑 HTML 页面,因为它可能是任何带有 HTML 文本框或可编辑字段的通用网页。

到目前为止我的代码:

//the menu item
    var menuItem_insert = chrome.contextMenus.create({"title": "Insert Timestamp", "contexts":[context], "onclick:": insertTimestamp}); 

//the onclick
    function insertTimestamp(info, tab) {
      //if info.editable is true then
      alert(info.editable); //for debugging

    //CODE GOES HERE: need to insert timestamp here
    }

问题: 如何将文本插入我可能没有“ID”的选定文本框中?

【问题讨论】:

  • PS,ajax 纯javascript。并且与你想在这里做什么无关。
  • 你想做什么something like this?

标签: javascript google-chrome-extension contextmenu


【解决方案1】:

avril alejandro回答不错,这是解决问题的另一种方法

逻辑是,当用户单击您的上下文菜单项时,菜单将消失,并且焦点回到您需要它的位置,右键单击开始的源元素(如果用户单击某个位置,也从该元素中的任何点开始在现有文本的中间)
您需要做的就是模拟复制/粘贴操作。

所以,在后台脚本中:

  • 在您的onClicked 监听器中创建textarea
  • 填入你想插入的值(本例中为日期字符串)
  • 聚焦并选择它
  • 使用document.execCommand('Copy')taxarea 值放入剪贴板
  • 如果点击是从 iframe 开始的,请确保您只定位该框架,以避免多个脚本插入和错误
  • 将脚本注入发件人选项卡(您拥有来自onClicked 侦听器的所有信息)
  • 注入的脚本只会做一件事,粘贴剪贴板中的内容document.execCommand('paste')

background.js

chrome.contextMenus.onClicked.addListener(function(info, tab) {
    var tArea = document.createElement('textarea'), _frame = null, date = new Date();
    document.body.appendChild(tArea);
    tArea.value = date.toLocaleString();
    tArea.focus();
    tArea.select();
    document.execCommand('copy');

    if(info.frameId) _frame = info.frameId;

    chrome.tabs.executeScript(tab.id, {frameId: _frame, matchAboutBlank: true, code: 
        "document.execCommand('paste');"
    }, function() {
        if (chrome.runtime.lastError) console.log(chrome.runtime.lastError);
        document.body.removeChild(tArea);
    });     
});

在您的清单中添加 "clipboardWrite", "clipboardRead", "activeTab" 权限

我在我的Opera notes extension 中使用了这个逻辑。
我从未见过有人使用这个技巧,而且它非常简单,而且它可以消除定位正确元素、选择、范围、富文本编辑器等所有麻烦

【讨论】:

    【解决方案2】:

    通过 document.activeElement 可以引用当前活动元素:

    document.activeElement.value = 'My value';
    

    应将“我的值”字符串放入您在调用时选择的输入文本中。

    不幸的是,在您的情况下,您希望在单击按钮后发生这种情况,因此您的活动元素将在单击时成为您的按钮。 因此,您可以找到一种解决方法来定义文本输入的元素onblur,以便单击按钮您将引用该输入文本。 所以这是 HTML

    <div>
      <input type="text" onblur="trackElement(this)" />
      <button onclick="test()">
      Test
      </button>
    </div>
    

    这是 JS:

    var myTxt = null;
    
    function test() {
        if (myTxt != null) {
        myTxt.value = 'my value';
      }
    }
    
    function trackElement(el) {
        console.log(el);
        myTxt = el;
    }
    

    https://jsfiddle.net/2459g8z5/4/

    【讨论】:

    • 嘿@quirimmo 感谢您的解释,这是有道理的,我看到的唯一问题是您假设我能够修改我想要执行此操作的页面的 html 代码操作...不幸的是,我无法修改该页面以添加 onclick 属性或其他任何内容。
    • 抱歉,我以为您可以更改 HTML。你能粘贴你得到的HTML代码吗?我会给你写一个选择器来检索你想要的元素
    • 我刚刚检查过...看起来我可能有文本框元素的 ID。我正在测试document.getElementById("id_here").value= "my_timestamp,但它没有替换文本...
    • 这段代码是正确的,所以它应该可以工作。你能把所有的例子都贴给我吗?
    【解决方案3】:

    according this reply
    您可以使用mousedown 事件侦听器注入内容脚本并存储被点击的元素:

    manifest.json

    ..
    "permissions": ["contextMenus"],
    "background": {
      "scripts": ["./bg.js"]
    },
    "content_scripts": [{
      "js": ["./content.js"],
      "matches": ["<all_urls>", "http://*/*" , "https://*/*", "file:///"],
      "run_at": "document_end"
    }],
    "manifest_version": 2
    ..
    

    background.js

    function mycallback(info, tab) {
      if (info.editable) {
        chrome.tabs.sendMessage(tab.id, {
          "text": "TEXT GOES HERE"
        });
      }
    }
    chrome.contextMenus.create({
      title: "Insert Timestamp",
      contexts: ["editable"],
      onclick: mycallback
    });
    

    content.js

    var clickedEl = null;
    document.addEventListener("mousedown", function (event) {
      //right click
      if (event.button == 2) {
        clickedEl = event.target;
      }
    }, true);
    chrome.runtime.onMessage.addListener(function (request) {
      clickedEl.value = request.text;
    });
    

    【讨论】:

      猜你喜欢
      • 2014-09-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-12-04
      • 1970-01-01
      相关资源
      最近更新 更多