Last active
October 25, 2022 17:31
-
-
Save asika32764/67d796184b9711b8bc3b4d8f0ab6be4f to your computer and use it in GitHub Desktop.
TinyMCE fetch remote images to local
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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