Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Property 'share' does not exist on type 'Navigator'

I need to use WebShareAPI in my Ionic application.

Here is my code as suggested in Introducing the Web Share API

if (window.navigator && window.navigator.share) {
  window.navigator.share({
    title: 'title',
    text: 'description',
    url: 'https://soch.in//',
  })
    .then(() => console.log('Successful share'))
    .catch((error) => console.log('Error sharing', error));
} else {
  alert('share not supported');
}

However, Typescript compilation fails with the following error:

[11:31:11]  typescript: src/pages/channel_home/channel_home.ts, line: 89
            Property 'share' does not exist on type 'Navigator'.

There is a likely reason explained here DOM lib: add support for navigator.share

However, I would like to know some workaround to make WebShareApi work in my Ionic app in particular, and in any Angular or Typescript app in general.

like image 760
pradeep Avatar asked Dec 15 '17 11:12

pradeep


4 Answers

Based on this answer, you can try to define a variable of type any and assign to it your value of Type Navigator. The isssue is related to typeScript typings.

let newVariable: any;

newVariable = window.navigator;

if (newVariable && newVariable.share) {
  newVariable.share({
    title: 'title',
    text: 'description',
    url: 'https://soch.in//',
  })
    .then(() => console.log('Successful share'))
    .catch((error) => console.log('Error sharing', error));
} else {
  alert('share not supported');
}

Another option would be to extend the interface Navigator as it is suggested in the link I posted above.

like image 135
edkeveked Avatar answered Nov 17 '22 23:11

edkeveked


For anyone looking for a proper answer, just add this to your global.d.ts file:

type ShareData = {
    title? : string;
    text? : string;
    url? : string;
};

interface Navigator
{
    share? : (data? : ShareData) => Promise<void>;
}

This properly reflects the level 1 API.

like image 35
DASPRiD Avatar answered Nov 17 '22 23:11

DASPRiD


Declare navigator as any

(window.navigator as any).share
like image 12
Matt Avatar answered Nov 17 '22 23:11

Matt


This also works and we don't need to create a newVariable.

if (window.navigator && window.navigator.share) {
  window.navigator['share']({
    title: 'title',
    text: 'description',
    url: 'https://soch.in//',
  })
    .then(() => console.log('Successful share'))
    .catch((error) => console.log('Error sharing', error));
} else {
  alert('share not supported');
}
like image 5
Avinash Avatar answered Nov 18 '22 00:11

Avinash