Skip to content

Instantly share code, notes, and snippets.

@jdtornow
Created January 3, 2024 15:55
Show Gist options
  • Save jdtornow/1d968269a3730f7ce087f3b9b80735cb to your computer and use it in GitHub Desktop.
Save jdtornow/1d968269a3730f7ce087f3b9b80735cb to your computer and use it in GitHub Desktop.
Stimulus Controller for Browser Native Share Sheet
export default class extends ApplicationController {
static classes = ['hidden']
static values = {
enabled: Boolean,
link: String
}
connect () {
if (!this.hasLinkValue) {
return
}
this.enabledValue = this.supportsNativeShareSheet
}
get supportsNativeShareSheet () {
const supportsNavigator = 'navigator' in window
if (supportsNavigator !== true) {
return false
}
if (typeof window.navigator.canShare !== 'function') {
return false
}
return window.navigator.canShare({ url: this.linkValue })
}
enabledValueChanged () {
if (this.enabledValue) {
this.element.classList.remove(...this.hiddenClasses)
} else {
this.element.classList.add(...this.hiddenClasses)
}
}
async share (event) {
if (event) {
event.preventDefault()
}
if (!this.enabledValue) {
return false
}
try {
await window.navigator.share({
url: this.linkValue
})
} catch (_) {
// user didn't share, no need to raise exception
}
}
}
<button class="hidden inline-block p-0 m-0 appearance-none bg-transparent border-none" type="button" data-controller="native-share" data-native-share-hidden-class="hidden" data-native-share-link-value="https://example.com" data-action="native-share#share">
<svg class="w-6 h-6" width="16" height="16" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor">
<path fill-rule="evenodd" d="M15.75 4.5a3 3 0 1 1 .825 2.066l-8.421 4.679a3.002 3.002 0 0 1 0 1.51l8.421 4.679a3 3 0 1 1-.729 1.31l-8.421-4.678a3 3 0 1 1 0-4.132l8.421-4.679a3 3 0 0 1-.096-.755Z" clip-rule="evenodd"></path>
</svg>
</button>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment