I am trying to build a webpage that will use an HTML form to upload an image file. Once uploaded, my goal is to convert this image to a favicon, and make it the favicon of the current page. Is there a way to use vanilla JavaScript to achieve this?
If converting to an image to a favicon is not possible with JavaScript on its own, would it be possible to upload a ".ico" file instead, and make it the favicon of the current page?
Vanilla JavaScript is a term used to mean "JavaScript + APIs provided by web browsers", so it can't do the upload part.
You can read the file with a FileReader, and then assign the resulting data:
scheme URL as the favicon.
Note that this demo will run, but you won't see the result because the favicon is set on a document loaded inside a frame and not on the SO page it runs in.
document.querySelector('input').addEventListener('change', e => {
const { files } = e.target;
const reader = new FileReader();
reader.addEventListener('load', e => {
const url = reader.result;
console.log(url); // For the sake of this demo
document.querySelector('link[rel=icon]').href = url;
});
// This would benefit from error handling in case a file wasn't selected or it wasn't an image
reader.readAsDataURL(files[0]);
});
<link rel="icon">
<input type=file>
Obviously, this won't persist unless you do something to make it persist (like storing it in local storage and then checking to see if an image is stored there when the page is loaded again.
If you want to upload it then you'll need to send the data to the server. The easiest way to do that is to just have a regular form submission, but you could also use Ajax.
Then you'll need code to store it on the server and add it to the webpage next time someone requests it. The specifics of that really depend on you existing server-side environment.