Uncaught SyntaxError: Unexpected identifier - Webshare api


#1

Hi,
I am trying to implement web share api of android chrome in jekyll posts page. Below is my code.

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

  });

</script>

But I get an Uncaught SyntaxError: Unexpected identifier error in console on line title: {{ page.title }},. Please correct my code. thanks.


#2

where are you putting that code? in its own file? or an include? or in a post/page?

Since the error has {{page.title}} in it you know that the liquid code isn’t being rendered for some reason.


#3

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 null error in console.
https://govtexam.justinechacko.in/maharashtra/2018/12/29/11.html


#4

It resolved by adding js code after html code. New problem is when I add text: '{{ page.content }}', after title: '{{ page.title }}', I get Uncaught SyntaxError: Invalid or unexpected token in console.


#5

Fixed it with template literal