output-frame.ts

68 lines | 2.008 kB Blame History Raw Download
import { BaseElement } from "../_base";
import './output-frame.less';
import watchConsole from './injects/watch-console.txt';
import tryCatch from './injects/try-catch.txt';
import onError from './injects/on-error.txt';
import windowStopScript from './injects/window-stop.txt';
import { NotificationBubbles } from "../notification-bubbles/notification-bubbles";

export class OutputFrame extends BaseElement {
    public Iframe: HTMLIFrameElement | null = null;
    private watchConsoleScript: string;

    constructor() {
        super();
        this.watchConsoleScript = watchConsole;
    }

    onInit(): void {
        this.reset();
    }

    onUpdate(): void {
    }

    reset() {
        if (this.Iframe && this.hasChild(this.Iframe)) {
            this.removeChild(this.Iframe);
        }

        this.Iframe = document.createElement("iframe");
        this.Iframe.setAttribute("sandbox", "allow-pointer-lock allow-same-origin allow-scripts");

        this.appendChild(this.Iframe);

        var bubbles = <NotificationBubbles>this.find("notification-bubbles");
        bubbles.reset();
        
        this.setInitScript(windowStopScript);
        this.setInitScript(onError);
        this.setInitScript(watchConsole);
    }

    preventInfiniteLoop(value: string) {
        return value.replace("while (true)", "while (false)");
    }

    private setInitScript(value: string) {
        var script: HTMLScriptElement = document.createElement("script");
        script.setAttribute("async", "");
        script.innerHTML = this.preventInfiniteLoop(value);

        this.Iframe?.contentWindow?.document.body.appendChild(script);
    }

    setScript(value: string) {
        this.reset();

        var script: HTMLScriptElement = document.createElement("script");
        script.setAttribute("async", "");
        script.innerHTML = this.preventInfiniteLoop(value);

        this.Iframe?.contentWindow?.document.body.appendChild(script);
    }

    surroundTryCatch(value: string) {
        return tryCatch.replace("[replace]", value);
    }
}