我正在根据不和情况发展一种 Chrome子延伸。
I used this piece of code, but still couldn t modify the content of the input box.
const inputBoxElem = document.querySelectorAll( [contenteditable="true"] )[1]
function replaceValue(selector, value) {
const el = selector;
if (el) {
el.focus();
document.execCommand( selectAll );
if (!document.execCommand( insertText , false, value)) {
el.value = new text ;
}
el.dispatchEvent(new Event( change , {bubbles: true}));
}
return el;
}
replaceValue(inputBoxElem, "Hello")
我想通过选择所有案文和历史新内容来修改投入箱的内容,但不能作修改。
(async () => {
let node = document.activeElement;
if (!node) {
return;
}
while (node.shadowRoot) {
node = node.shadowRoot.activeElement;
}
const initText = getNodeText(node);
if (!isEditAbleNode(node)) {
return;
}
let text = "hello, change input box content";
try {
if (isInputNode(node)) {
node.value = text;
node.dispatchEvent(
new Event("input", { bubbles: true, cancelable: true })
);
return;
}
selectContent(node);
await sleep(200);
pasteContentEvent(node, text);
await sleep(200);
if (getNodeText(node).startsWith(initText)) {
pasteContentCommand(node, text);
await sleep(100);
} else {
collapseToEnd(node);
}
} catch (err) {
console.log("error: ", err.message);
} finally {
}
})();
function isInputNode(node) {
return node.nodeName === "INPUT" || node.nodeName === "TEXTAREA";
}
function isEditAbleNode(node) {
return node.hasAttribute("contenteditable");
}
function selectContent(node) {
node.focus();
const range = document.createRange();
range.selectNodeContents(node);
const selection = window.getSelection();
selection.removeAllRanges();
selection.addRange(range);
}
function pasteContentEvent(node, text) {
node.focus();
const data = new DataTransfer();
data.setData("text/plain", text);
const event = new ClipboardEvent("paste", { clipboardData: data });
document.dispatchEvent(event);
data.clearData();
}
function pasteContentCommand(node, text) {
node.focus();
document.execCommand("insertText", false, text);
}
function collapseToEnd(node) {
node.focus();
const selection = window.getSelection();
selection.collapseToEnd();
}
function getNodeText(node) {
if (isInputNode(node)) {
return node.value;
}
return node.innerText || node.textContent || "";
}
function sleep(delay) {
new Promise((resolve) => {
const timer = setTimeout(() => {
clearTimeout(timer);
resolve();
}, delay);
});
};