Skip to content

Instantly share code, notes, and snippets.

@christineywang
Last active March 28, 2018 20:45
Show Gist options
  • Save christineywang/0c0b952340ad059b8bc5c08ac2370167 to your computer and use it in GitHub Desktop.
Save christineywang/0c0b952340ad059b8bc5c08ac2370167 to your computer and use it in GitHub Desktop.
ui extension
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<!-- UI Extensions CSS -->
<link rel="stylesheet" href="//contentful.github.io/ui-extensions-sdk/cf-extension.css">
<!-- UI Extensions SDK -->
<script src="//contentful.github.io/ui-extensions-sdk/cf-extension-api.js"></script>
<style>
</style>
</head>
<body>
<!-- Custom markup of the UI Extension -->
<button id="randomImage" class="cf-btn-primary">Generate Random Image</button>
<!-- Custom logic of the UI Extension -->
<script>
const cfExt = window.contentfulExtension || window.contentfulWidget;
cfExt.init(api => {
const urlField = api.entry.fields.url;
const randomImage = document.querySelector('#randomImage');
randomImage.addEventListener('click', () => {
const key = 'unsplash';
const url = `https://source.${key}.com/random/2560x1440`;
let bloburl = void 0;
let img = new Image();
const getResourceName = fetch(url)
.then(response => Promise.all([response.url, response.blob()]))
.then(([resource, blob]) => {
bloburl = URL.createObjectURL(blob);
img.src = bloburl;
return resource;
});
getResourceName.then(res => res).catch(err => console.log(err));
urlField.removeValue();
urlField.setValue(res);
});
});
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment