Share from website – Web Share API | share anything from the website







Share from the website –  Web Share API | share anything from the website

Welcome🎉 to Code With Random blog. In this blog, we learn that how we create a share anything from the website. We use HTML, Css, and javascript to share anything from the website. Hope you enjoy our blog so let’s start with a basic HTML structure for a shared anything from the website here is the best example. 

HTML code

 <button id="btn">Demo of Web Share API</button>  

There is all HTML code for the share anything from the website. Now, you can see output without CSS, then we write css & javascript for sharing anything from the website.

output

Share from website -  Web Share API | share anything from the website

CSS Code

 :root {  
--background-color: #212121;
--text-color: #fff;
--font: sans-serif;
}
* {
margin: 0;
padding: 0;
}
body {
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
background: var(--background-color);
font-family: var(--font);
color: var(--text-color);
}
#btn {
padding: 0.7rem 1.5rem;
border: none;
font-size: 1em;
border-radius: 5px;
cursor: pointer;
margin: 20px;
transition: 100ms ease-in-out;
background-color: #2ea44f;
color: white;
border: 2px solid #2ea44f;
}
#btn:hover {
background-color: transparent;
color: #2ea44f;
}

Now we have completed our CSS section,  Here is our updated output CSS.

output

Share from website -  Web Share API | share anything from the website

Javascript code 

 const btn = document.getElementById("btn");  
// function for web share api
function webShareAPI(header, description, link) {
navigator
.share({
title: header,
text: description,
url: link
})
.then(() => console.log("Successful share"))
.catch((error) => console.log("Error sharing", error));
}
if (navigator.share) {
// Show button if it supports webShareAPI
btn.style.display = "block";
btn.addEventListener("click", () =>
webShareAPI("header", "description", "www.url.com")
);
} else {
// Hide button if it supports webShareAPI
btn.style.display = "none";
console.error("Your Browser doesn't support Web Share API");
document.write("Your Browser doesn't support Web Share API");
}

Final output

Share from website -  Web Share API | share anything from the website


Now we have completed our javascript section,  Here is our updated output with javascriptHope you like the  share anything from the website. you can see output video and project screenshots. See our other blogs and gain knowledge in front-end development. Thank you 🙏💕!

In this post, we learn how to create a  share anything from the website using simple HTML & CSS, and javascript. If we made a mistake or any confusion, please drop a comment to reply or help you in easy learning.

Written by – Code With Random/Anki 

Share on:

Leave a Comment