Categories
JavaScript Answers

How to convert Base64 String to JavaScript file object like as from file input form?

To convert Base64 String to JavaScript file object like as from file input form, we use fetch.

For instance, we write

const url = "data:image/png;base6....";
const res = await fetch(url);
const blob = await res.blob();
const file = new File([blob], "File name", { type: "image/png" });

to call fetch with the base64 URL.

Then we call res.blob to return a promise with the blob response.

Finally, we create a file with the blob with the File constructor.

Categories
HTML

How to force browser to download image files on click with HTML?

To force browser to download image files on click with HTML, we add the download attribute.

For instance, we write

<a href="/path/to/image.png" download> download </a>

to add the download attribute to make the image at the path download instead of opening it.

Categories
JavaScript Answers

How to fix HTML5 localStorage error with Safari: “QUOTA_EXCEEDED_ERR: DOM Exception 22: An attempt was made to add something to storage that exceeded the quota.” with JavaScript?

To fix HTML5 localStorage error with Safari: "QUOTA_EXCEEDED_ERR: DOM Exception 22: An attempt was made to add something to storage that exceeded the quota." with JavaScript, we check if the entry with the key can be saved.

For instance, we write

const isLocalStorageNameSupported = (testKey) => {
  const storage = window.localStorage;
  try {
    storage.setItem(testKey, "1");
    storage.removeItem(testKey);
    return true;
  } catch (error) {
    return false;
  }
};

to define the isLocalStorageNameSupported function.

In it, we get the testKey string and call setItem with it to see if we can save the entry with the key without error.

We call removeItem to remove the test entry.

If there’s an error we return false.

Categories
JavaScript Answers

How to load scripts asynchronously with JavaScript?

To load scripts asynchronously with JavaScript, we use the async or defer attributes.

For instance, we write

<script async src="script.js" onload="myInit()"></script>

or

<script defer src="script.js" onload="myInit()"></script>

to load script.js asynchronously.

Categories
JavaScript Answers

How to use querySelector with IDs that are numbers with JavaScript?

To use querySelector with IDs that are numbers with JavaScript, we add '#\\3' before the number.

For instance, we write

const el = document.querySelector("#\\31 ");

to select the element with ID 1 with querySelector.