Search code examples
javascriptangularwebsharenavigator

Navigator.share not work in Angular, but work in a test in codepen


I have a problem with a navigator.share.

I test this code in codepen:

if (navigator.share) {
        navigator.share({
            title: 'Web Fundamentals',
            text: 'Check out Web Fundamentals — it rocks!',
            url: 'https://developers.google.com/web',
        })
          .then(() => console.log('Successful share'))
          .catch((error) => console.log('Error sharing', error));
      } else {
        console.log('no share');
      }
}

https://codepen.io/cookienawer/pen/ZEzpYrW?editors=1010

And in my mobile device work.

But when I put this code in my app with Angular does not go inside the if.

Also I test canShare method, because this is a test, but I want share images. Images that stay in DOM with tag, but this is another problem...

The question is I can share anything in codepen but not in Angular app.

I have fount that for use navigator in angular I have to put this code before navigator:

let varNavigator: any;

varNavigator = window.navigator; 
if (varNavigator.share) {
 ...

If I direcly do varNavigator.share it show this error:

core.js:1427 ERROR TypeError: (intermediate value)(intermediate value).share is not a function
    at e._next (home.component.ts:299)
    at e.__tryOrUnsub (Subscriber.js:239)
    at e.next (Subscriber.js:186)
    at e._next (Subscriber.js:127)
    at e.next (Subscriber.js:91)
    at e.notifyComplete (ForkJoinObservable.js:197)
    at e._complete (InnerSubscriber.js:32)
    at e.complete (Subscriber.js:116)
    at e._complete (Subscriber.js:134)
    at e.complete (Subscriber.js:116)

I get the code from the URLs:

https://developers.google.com/web/updates/2016/09/navigator-share https://developers.google.com/web/updates/2019/05/web-share-files


Solution

  • You could try this

    const navigator = window.navigator as any;
    
    if (navigator.share) {
      navigator
        .share({
          title: 'Google',
          text: 'Save',
          url: 'https://google.com'
        })
        .then(() => console.log('Successful share'))
        .catch(error => console.log('Error sharing', error));
    } else {
      alert('share not supported');
    }
    

    Also... make sure that you deliver the site on https (or localhost)