Thanks for the code! I used it to let users share the website URL (in my case, sustainable deals on mobile view)
Here is the adjusted custom code to share the page URL:
<!DOCTYPE html>
<html lang="en">
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style>
body, html {
margin: 0;
padding: 0;
width: 100%;
overflow-x: hidden;
}
.button-container {
}
#share {
background-color: #FEF8EE;
border: 1px solid #FFA500;
border-radius: 6px;
color: #333333;
display: block;
width: 100%; /* Make button full width */
font-family: Arial, sans-serif;
font-size: 14px;
font-style: normal;
font-weight: 450;
line-height: 20px;
padding: 8px 12px;
box-sizing: border-box; /* Ensure padding doesn't cause overflow */
cursor: pointer;
}
</style>
</head>
<body>
<div class="button-container">
<button id="share">Share this deal</button>
</div>
<script>
// Asynchronous function to handle the button click
const handleClick = async () => {
try {
// Get the current URL
const currentUrl = window.location.href;
// Prepare the share data
const shareData = {
title: document.title,
text: 'Check out this page!',
url: currentUrl
};
// Check if the navigator can share and proceed
if (navigator.share) {
await navigator.share(shareData);
} else {
// Fallback for browsers that don't support Web Share API
alert('Share this link: ' + currentUrl);
// Optionally, copy to clipboard
await navigator.clipboard.writeText(currentUrl);
alert('Link copied to clipboard!');
}
} catch (error) {
console.error('Error:', error.message);
}
};
// Add the click event listener to the button
document.getElementById('share').addEventListener('click', handleClick);
</script>
</body>
</html>