Navigator.share在Angular中不起作用,但在Codepen中的测试中起作用

问题描述 投票:0回答:1

我在navigator.share上有问题。

我在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

在我的移动设备上工作。

但是当我将此代码与Angular一起放入我的应用程序时,不会放在if中。

另外,我还测试了canShare方法,因为这是一个测试,但是我想共享图像。带有标签的DOM中保留的图像,但这是另一个问题...

问题是我可以在Codepen中共享任何内容,但不能在Angular应用程序中共享。

我发现要在角度使用导航器,必须将此代码放在导航器之前:

let varNavigator: any;

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

如果我直接执行varNavigator.share,它将显示此错误:

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)

我从URL获得代码:

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

javascript angular web share navigator
1个回答
0
投票

您可以尝试这个

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');
}

也...确保您在https(或localhost)上交付站点

© www.soinside.com 2019 - 2024. All rights reserved.