Skip to content

Instantly share code, notes, and snippets.

@kohlerdominik
Last active March 13, 2024 07:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kohlerdominik/b563f8a1f7178b418316c62ecd042c5b to your computer and use it in GitHub Desktop.
Save kohlerdominik/b563f8a1f7178b418316c62ecd042c5b to your computer and use it in GitHub Desktop.
Google Cloud Storage Bucket - List all files in the bucket in the Browser (HTML/Javascript)
[
{
"maxAgeSeconds": 60,
"method": [
"GET"
],
"origin": [
"*"
],
"responseHeader": [
"Accept",
"Content-Type"
]
}
]
<!DOCTYPE html>
<html>
<head>
<title>File List</title>
</head>
<body>
<h1>File List</h1>
<ul id="bucket-list"></ul>
<script>
if (location.protocol !== "https:") {
location.protocol = "https:";
}
const publicUrl = window.location.href;
const bucketId = publicUrl.replace(/^https?:\/\//, "");
const bucketUrl = `https://storage.googleapis.com/${bucketId}`;
fetch(bucketUrl)
.then((response) => response.text())
.then((xmlString) => {
const parser = new DOMParser();
const xmlDoc = parser.parseFromString(xmlString, "text/xml");
const items = xmlDoc.querySelectorAll("Contents > Key"); // Adjust selector if needed
const listItems = Array.from(items)
.filter((item) => item.textContent.includes("/"))
.filter((item) => !item.textContent.endsWith("/"))
.map((item) => `<li>${publicUrl}${item.textContent}</li>`);
const bucketList = document.getElementById("bucket-list");
bucketList.innerHTML = listItems.join("");
})
.catch((error) =>
console.error("Error fetching or parsing XML:", error)
);
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment