我正在開發一個 chrome 擴展,我在頁面中的可編輯元素上使用背景關系選單。我獲取已執行右鍵單擊的元素,現在我想在該輸入元素中插入一個值。
我嘗試使用簡單的 :
document.activeElement.value="value"; 。
在這種情況下,將插入值,但它并不能完全復制用戶的鍵入操作。
例如:當用戶鍵入最少單個字符時,將啟用保存按鈕。但是當我們使用 document.activeElement.value 插入時,保存按鈕不會被啟用。它需要在輸入元素之外進行額外的手動單擊,或者需要在輸入區域內手動按下其他鍵。
我嘗試使用 KeyboardEvent 來模擬右箭頭鍵按下,但它仍然沒有用。
有沒有其他方法可以實作這一目標?
Background.js 片段:
let myPromise = new Promise(function(myResolve, myReject) {
var ele=mycallback(info,tab);
myResolve(ele);
});
myPromise.then(
function(value){
});
} );
chrome.contextMenus.create({
title: "Length",
parentId: "tool",
contexts:["editable"],
id:"length"
});
chrome.contextMenus.create({
title: "1 character",
parentId: "length",
contexts:["editable"],
id:"1character"
});
function mycallback(info, tab) {
chrome.tabs.sendMessage(tab.id, info.menuItemId, {frameId: info.frameId}, data => {
return data.value;
});
}
Content.js 片段:
var clickedEl = null;
document.addEventListener("contextmenu", function(event){
clickedEl = event.target;
}, true);
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
document.activeElement.value="";
switch(request){
case '1character':
document.activeElement.value="Q";
break;
}
sendResponse({value: clickedEl.value});
});
以下是手動輸入和以編程方式插入之間的區別:
手冊: 作業正常
當我們以編程方式填充時: 需要在區域外單擊或按一些鍵以顯示建議
uj5u.com熱心網友回復:
您需要在 DOM 樹中向上傳播您的更改,這就是需要Event bubbling救援的地方。
想知道什么是事件冒泡?給你,
W3 參考冒泡事件屬性
MDN 參考事件冒泡和捕獲
注意:Event bubbling可能很有用,也可能導致意外問題。
下面的片段將做你正在尋找的 -
document.activeElement.value="Q";
document.activeElement.dispatchEvent(new Event('input', { bubbles: true }));
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/483368.html
標籤:javascript html 谷歌浏览器
