Merge pull request #82 from lmccart/console

fixing console.log outside setup/draw closes #78
This commit is contained in:
Cassie Tarakajian 2016-08-30 21:15:03 -04:00 committed by GitHub
commit 6a3f3a7cf0
1 changed files with 57 additions and 51 deletions

View File

@ -4,7 +4,7 @@ import escapeStringRegexp from 'escape-string-regexp';
import srcDoc from 'srcdoc-polyfill';
const startTag = 'filestart-';
const startTag = '@fs-';
function getAllScriptOffsets(htmlFile) {
const offs = [];
@ -29,24 +29,9 @@ function getAllScriptOffsets(htmlFile) {
return offs;
}
function hijackConsoleScript(offs) {
function hijackConsoleLogsScript() {
const s = `<script>
function getScriptOff(line) {
var offs = ${offs};
var l = 0;
var file = '';
for (var i=0; i<offs.length; i++) {
var n = offs[i][0];
if (n < line && n > l) {
l = n;
file = offs[i][1];
}
}
return [line - l, file];
}
document.addEventListener('DOMContentLoaded', function() {
var iframeWindow = window;
var originalConsole = iframeWindow.console;
iframeWindow.console = {};
@ -62,7 +47,7 @@ function hijackConsoleScript(offs) {
var args = Array.from(arguments);
args = args.map(function(i) {
// catch objects
return (typeof i === 'undefined') ? 'undefined' : JSON.stringify(i);
return (typeof i === 'string') ? i : JSON.stringify(i);
});
// post message to parent window
@ -73,6 +58,24 @@ function hijackConsoleScript(offs) {
}, '*');
};
});
</script>`;
return s;
}
function hijackConsoleErrorsScript(offs) {
const s = `<script>
function getScriptOff(line) {
var offs = ${offs};
var l = 0;
var file = '';
for (var i=0; i<offs.length; i++) {
var n = offs[i][0];
if (n < line && n > l) {
l = n;
file = offs[i][1];
}
}
return [line - l, file];
}
// catch reference errors, via http://stackoverflow.com/a/12747364/2994108
window.onerror = function (msg, url, lineNumber, columnNo, error) {
@ -93,7 +96,6 @@ function hijackConsoleScript(offs) {
}, '*');
return false;
};
});
</script>`;
return s;
}
@ -144,6 +146,9 @@ class PreviewFrame extends React.Component {
// have to build the array manually because the spread operator is only
// one level down...
htmlFile = hijackConsoleLogsScript() + htmlFile;
const jsFiles = [];
this.props.jsFiles.forEach(jsFile => {
const newJSFile = { ...jsFile };
@ -195,7 +200,8 @@ class PreviewFrame extends React.Component {
}
scriptOffs = getAllScriptOffsets(htmlFile);
htmlFile += hijackConsoleScript(JSON.stringify(scriptOffs));
htmlFile += hijackConsoleErrorsScript(JSON.stringify(scriptOffs));
return htmlFile;
}