Skip to content

Instantly share code, notes, and snippets.

@asika32764
Last active October 25, 2022 17: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 asika32764/67d796184b9711b8bc3b4d8f0ab6be4f to your computer and use it in GitHub Desktop.
Save asika32764/67d796184b9711b8bc3b4d8f0ab6be4f to your computer and use it in GitHub Desktop.
TinyMCE fetch remote images to local
editor.on('PastePostProcess', (e) => {
setTimeout(async () => {
const doc = new DOMParser().parseFromString(editor.getContent(), `text/html`);
const promises = [];
for (const img of doc.querySelectorAll('img')) {
const src = img.src;
const p = new Promise((resolve) => {
fetch(src)
.then(response => response.blob())
.then(blob => {
const reader = new FileReader() ;
reader.addEventListener('load', () => {
img.src = reader.result;
resolve();
});
reader.readAsDataURL(blob) ;
});
});
promises.push(p);
}
await Promise.all(promises);
// Keep cursor position and replace
const bookmark = editor.selection.getBookmark(2, true);
editor.setContent(doc.body.innerHTML);
editor.selection.moveToBookmark(bookmark);
}, 0);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment