Search code examples
google-chrome-extension

chrome extension content.js file loads too early: unable to find an element in DOM


I'm trying to add a listener to the linkedIn 'create post' button through a chrome extension

Now, because I added a timeout, the button is found, but if I run it directly or with a smaller timeout (eg 1000ms) the button is not found

Here's my code:

function findStartPostField() {
  const lnCssSelector = '.share-box-feed-entry__trigger'
  let button = document.querySelector(lnCssSelector)
  console.log('button found ', button)
  if (button)
    button.addEventListener('click', () => alert('clicked'))
}

setTimeout(findStartPostField, 5000)

console.log('content js loaded, registering message listener');

In my manifest, I tried run_at with document_end and document_idle values without success.

I don't like the idea of having to put a timeout. Is there an event like 'onload' that would trigger when all JS has finished executing (somehow saying the document is rendered and ready)


Solution

  • Here's an implementation based on wOxxOm's comment.

    document.body.addEventListener('click', (e) => {
      if (e.target.className == 'share-box-feed-entry__trigger') {
        alert('clicked');
      }
    })