我正在尝试创建一个允许用户使用预定义文本填充输入字段的扩展。用户应右键单击输入字段,选择选项,代码必须自动设置文本。
经过一些搜索,我知道我需要使用内容脚本,但我不知道如何找到选定的输入字段并更改文本。
事件.js
chrome.contextMenus.create({
id: "context_positive",
title: "✔ Positief",
contexts: ["all"]
});
chrome.contextMenus.onClicked.addListener(function(info, tab) {
if (tab) {
if (info.menuItemId === "context_positive"){
// Call content script and get it to locate the source element and set text value
}
}
});
content_script.js
由于您单击了输入字段,因此应该可以使用 document.activeElement 访问它,但在测试期间它通常只会选择 BODY 作为 activeElement..
document.activeElement.innerHTML = "test";
所以我不确定如何从 event.js 操作转到 content_script.js 部分以在选定的输入字段中输入文本。关于如何进行的任何建议?
最佳答案
您可以利用点击事件:
let input = document.querySelector("input");
document.querySelector(".editable").addEventListener("click", function(event) {
let element = event.target;
if (element.innerText) {
element.innerText = input.value;
}
});
<div class="editable">
<span>Example text one</span>
<p>Example text two</p>
<div>
<span>Child text example one</span>
<span>Child text example two</span>
</div>
<div>Example text three</div>
</div>
<br><br>
Text to replace: <input type="text">
关于javascript - Chrome 扩展 - 设置点击元素的文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58330520/