Home > front end >  How to insert a value into a editable element present in a page through JS?
How to insert a value into a editable element present in a page through JS?

Time:05-30

Am developing a chrome extension in which i use context menu on editable elements in a page. I fetch the element on which right click has been performed and now i want to insert a value into that input element.

I tried using the simple : document.activeElement.value="value"; .

In this case, value will be inserted but it doesn't exactly replicate the typing action of user.

For example : Save button will be enabled when user types a minimum of single character. But when we use document.activeElement.value to insert, save button wont be enabled. It requires an additional manual click outside the input element or requires pressing some other key manually inside the input area.

I tried using KeyboardEvent to simulate a right arrow key press but still it didn't work.

Is there any other way to achieve this ?

Background.js snippet :

    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 snippet :

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});
});

Below is the difference between manually entering and inserting programatically :

Manual : works fine

When we fill programatically : Needs a click outside the area or some key press to show suggestions

CodePudding user response:

You need to propagate your changes up in the DOM Tree and this is where Event bubbling comes into rescue.
Wondering what is Event Bubbling ? Here you go,
W3 Reference bubbles Event Property
MDN Reference Event bubbling and capture

Note: Event bubbling can be useful and can also cause unexpected problems.

Below snippet will do what you are looking for -

document.activeElement.value="Q";
document.activeElement.dispatchEvent(new Event('input', { bubbles: true }));
  • Related