-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
85 lines (77 loc) · 2.5 KB
/
Copy pathscript.js
File metadata and controls
85 lines (77 loc) · 2.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
const output = document.getElementById("output");
window.addEventListener("message", (event) => {
if (event.origin !== window.location.origin) return;
const data = event.data;
if (data.type === "log"){
console.log(data.data);
} else if (data.type === "error") {
console.error(data.data);
}
});
function runCode(mode = "mixed") {
const oldIframe = document.getElementById("output");
const newIframe = document.createElement("iframe");
newIframe.id = "output";
newIframe.className = oldIframe.className;
oldIframe.parentNode.replaceChild(newIframe, oldIframe);
const doc = newIframe.contentDocument || newIframe.contentWindow.document;
let html = "",
css = "",
js = "";
if (mode === "mixed") {
const content = mixedEditor.getValue();
const htmlMatch = content.match(/<body[^>]*>((.|\n)*?)<\/body>/i);
const cssMatch = content.match(/<style[^>]*>((.|\n)*?)<\/style>/i);
const jsMatch = content.match(/<script[^>]*>((.|\n)*?)<\/script>/i);
html = htmlMatch ? htmlMatch[1] : "";
css = cssMatch ? cssMatch[1] : "";
js = jsMatch ? jsMatch[1] : "";
} else if (mode === "separate") {
html = htmlEditor.getValue();
css = cssEditor.getValue();
js = jsEditor.getValue();
} else if (mode === "js-only") {
js = jsOnlyEditor.getValue();
html = '<h3 style="color:white;">Check the console</h3>';
}
const scriptInterceptor = `
<script>
(() => {
const __log = console.log;
const __error = console.error;
console.log = function(...args) {
parent.postMessage({ type: 'log', data: args.join(' ') }, '*');
__log.apply(console, args);
};
console.error = function(...args) {
parent.postMessage({ type: 'error', data: args.join(' ') }, '*');
__error.apply(console, args);
};
window.onerror = function(message, source, lineno, colno, error) {
parent.postMessage({
type: 'error',
data: message + ' at line ' + lineno + ', column ' + colno
}, '*');
};
})();
<\/script>
`;
const output = `
<!DOCTYPE html>
<html><head>
<style>${css}</style>
${scriptInterceptor}
</head><body>
${html}
<script>${js}<\/script>
</body></html>
`;
doc.open();
doc.write(output);
doc.close();
}
const refreshBtn = document.getElementById("refreshBtn");
refreshBtn.addEventListener("click", () => {
const mode = document.getElementById("editor-mode").value;
runCode(mode);
});