javascript - Chrome Extension: Placeholder Text Issue with XPath and ContentEditable - Stack Overflow

admin2025-04-25  2

I'm studying how to build an extension for Google Chrome, and my first project is to automatically send messages to a list of my clients via WhatsApp Web. I'm trying to accomplish this by getting the search box element using its XPath and inserting the contact information. However, I've encountered some challenges. Here's the code I'm using:

const waitTimeout = (ms) => new Promise(resolve => setTimeout(resolve, ms));

const typeInTextBox = async (selector, number) => {

let el = document.evaluate(selector,
  document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;

for (var i = 0; i < 5; i++) {
  el.focus();
  document.execCommand('selectAll');
  document.execCommand('insertText', false, number);
  el.dispatchEvent(new Event('change', {bubbles: true})); 
  el.blur();
  await waitTimeout(2000);

  if (el.textContent == number) {
    return true;
  }
}
return false;
}

await typeInTextBox('/html/body/div[1]/div/div/div[3]/div/div[2]/div[1]/span/div/span/div/div[1]/div[2]/div[2]/div/div', 'Hello World')

As can be seen from the image below, the code works partially. The contact information gets inserted into the search box, but the placeholder text does not disappear, and nothing happens.

It seems that the placeholder text disappears only when the search box is clicked, but this issue doesn't get resolved even by calling the click or focus function. Would there be some workaround for this?

The element retrieved by using the XPath is contenteditable attribute.

转载请注明原文地址:http://anycun.com/QandA/1745534312a90879.html