6

Here's a sample code:

HTML

<script> alert('This is alert!') </script>

JS

window.alert = function(data)  //alert() over-riding
{
    scriptObject = document.currentScript; //gives me <script> object
}

Update: The above code doesn't seem to work now (It worked earlier, compatibility removed for IE) in Internet Explorer 11.420.10586.0. Why it is able to find the Script object in Chrome, Firefox, Safari and Microsoft Edge, but not in Internet Explorer? Is there any alternate way?


Issue:

HTML

<script> ReferenceError.prototype.__defineGetter__('name', function fff() { javascript:alert(1) }),x </script>

JS

window.alert = function(data)  //alert() over-riding
{
    scriptObject = ? // I need to get the Script object
}

I tried arguments.callee.caller to find fff(), but unable to catch the script object.

Alert() doesn't execute in Chrome for the above script. Use Firefox, instead. I couldn't get the script object in any browser.

Any solution please?

2

1 Answer 1

1

In the simplest scenario when your overridden alert is invoked immediately in (blocking) script, simple document.scripts[document.scripts.length-1] could be good to go:

<pre id="log"></pre>


<script>
window.alert = function(a){
 log.innerText += a + ' ' + document.scripts[document.scripts.length-1].outerHTML + '\n';
}
</script>

<script id="a">alert('first')</script>

<script id="b">alert('second')</script>

<script id="c">alert('third')</script>

5
  • This works in IE. But, if there are too many scripts, say, in your example, some 100 scripts continuously, will it be deterministic? I mean the order of data in log. Also, please have a look at the second part issue ReferenceError alert. Commented Jun 23, 2016 at 13:22
  • 1
    As long as those scripts will be static (not inserted dynamically after load as not-last script in the document tree) and synchronous (not async), yes, it must be deterministic and guaranteed to work properly: from the single-thread nature of JavaSript. (I'm not sure about async TBH.)
    – myf
    Commented Jun 23, 2016 at 13:29
  • This cleared it. Thanks. Any idea about second part ReferenceError alert? Commented Jun 23, 2016 at 14:25
  • 1
    It seems a bit arcane to me, but generally I'd assume if you manage to override alert before the reference error override happens and is invoked, it should work the same. Dark prototype crippling aside, it is just call of some function, which, if redeclared in previous script block or file should be 'yours'.
    – myf
    Commented Jun 23, 2016 at 18:37
  • Yes, the over-ride happens and is invoked. The issue is actually traversing from alert to <script>. Finding arguments.callee.caller doesn't help in this case, it's going somewhere inside fff(), and I could never reach <script>. Commented Jun 24, 2016 at 10:20

Not the answer you're looking for? Browse other questions tagged or ask your own question.