Ad

Uncaught TypeError: Cannot Read Property 'addEventListener' Of Null In JavaScript Webshare Api

- 1 answer

I am trying to implement web share api of android chrome in jekyll posts page. Below is my code. my code is in _layout/post.html.

<script>
  document.querySelector('.share-btn2').addEventListener('click', function() {
    console.log('clicked');
    if(navigator.share) {
      navigator.share({
        title: '{{ page.title }}',
        url: {{ site.url }}{{ page.url }}
      })
      .then(() => console.log('Success'))
      .catch((error) => console.log('Error sharing', error));
    }

  });

</script>

<button class="btn btn-danger shadow-sm my-2 my-sm-0 share-btn2" type="submit" value="submit">More</button>.

Now I get Uncaught TypeError: Cannot read property 'addEventListener' of nullerror in console. https://govtexam.jus.in/maharashtra/2018/12/29/11.html

Ad

Answer

It seems like you are binding an event before the DOM is loaded. Just wrap it in with DOMContentLoaded event:

document.addEventListener("DOMContentLoaded", function(event) { // <-- add this wrapper
  document.querySelector('.share-btn2').addEventListener('click', function() {
    console.log('clicked');
    if (navigator.share) {
      navigator.share({
          title: '{{ page.title }}',
          url: '{{ site.url }}{{ page.url }}'
        })
        .then(() => console.log('Success'))
        .catch((error) => console.log('Error sharing', error));
    }

  });
}); // <---DOMContentLoaded closing
Ad
source: stackoverflow.com
Ad