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.
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.
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.
Declare navigator
as any
(window.navigator as any).share
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');
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With