Browser discrepancies when calling toString() on a JavaScript function with comments
February 6th, 2009I’ve been working on extracting some text out of a given JavaScript function when I realized that toString() may return parts of the original comments, depending on the browser. I’ve done a quick test to capture the behaviour of popular browsers. Here’s my test script:
function/*post-keyword*/fn/*post-name*/()/*post-parens*/{
/*inside*/
}
document.write(fn.toString());
And here are the results I got on different browsers:
| Browser | post-keyword | post-name | post-parens | inside |
|---|---|---|---|---|
| Firefox | No | No | No | No |
| Safari | No | No | No | No |
| Chrome | No | No | Yes | Yes |
| IE | Yes | Yes | Yes | Yes |
| Opera | Yes | Yes | Yes | Yes |
And out of the browser context:
| Engine | post-keyword | post-name | post-parens | inside |
|---|---|---|---|---|
| JScript | Yes | Yes | Yes | Yes |
| Rhino | No | No | No | No |
While looking for the best solution to extract the parts that I need, I’ve implemented a workaround. Sort of. If blocking the problem can be considered a workaround:
var functionToStringHasComments = /PROBE/.test(function () {/*PROBE*/});
// ...
if (functionToStringHasComments) {
throw "...";
}