import {isSafari, isStandalone} from './environment'; import escapeXML from '../common/escape-xml'; import {_} from '../locales'; const origin = isStandalone ? '*' : location.origin; const getPreviewSource = () => ` ${escapeXML(_.translate('preview.loading'))}
`; const windowToBlobMap = new WeakMap(); class Preview { constructor () { const preview = getPreviewSource(); // Safari does not let file: URIs used by standalone version to open blob: URIs // The desktop app just doesn't support windows loaded from blobs const canUseBlobWindow = !(isStandalone && isSafari) && typeof IsDesktop === 'undefined'; if (canUseBlobWindow) { const url = URL.createObjectURL(new Blob([preview], { type: 'text/html' })) + '#do-not-share-this-link-it-will-not-work-for-others'; this.window = window.open(url); } else { this.window = window.open('about:blank'); if (this.window) { this.window.document.write(preview); } } if (!this.window) { throw new Error('Cannot open popup'); } } setContent (content) { windowToBlobMap.set(this.window, content); this.window.postMessage({ blob: content }, origin); } setProgress (progress, text) { this.window.postMessage({ progress, text }, origin); } close () { this.window.close(); } } window.addEventListener('message', (e) => { if (origin !== '*' && e.origin !== location.origin) { return; } const data = e.data; if (data && data.preview === 'hello') { const source = e.source; const blob = windowToBlobMap.get(source); if (blob) { source.postMessage({ blob }, origin); } } }); export default Preview;