Reputation: 2220
Is it possible in some way to hack the behaviour of window.location.replace
, to fire a JavaScript function (let's say alert
) instead of making the user go to the new location?
I'll give you the example, let's say we have this function:
setTimeout(function(){ window.location.replace("#SOMETHING_HERE#"); }, 900);
this is fired when a user clicks on a specific button; the #SOMETHING_HERE#
is a placeholder, the administrator can put there a URL via a configuration panel.
Now, we all know clients are weird, and mine has just asked me to find a way to fire a JavaScript instead of redirect the user, well, I'm stuck. Of course I should modify the function bound to the button, but actually I have no access to the code and the only entry point is that panel I've mentioned before, I can only change the value of #SOMETHING_HERE#
.
Do someone has some clues on how I could for example fire an alert("foo"); ? is that possible in some way?
the answer could be also "NO" and I'll simply say them that we have to find a way to change that code.
Upvotes: 0
Views: 2264
Reputation: 32202
You can prefix your string with javascript:
:
setTimeout(function(){ window.location.replace("javascript:alert('hello world!')"); }, 900);
This works because the spec for location.replace
ends up at the definition for "navigate", which says:
- This is the step that attempts to obtain the resource, if necessary. Jump to the first appropriate substep:
...
If the new resource is a URL whose scheme is javascript
Queue a task to run these "javascript: URL" steps, associated with the active document of the browsing context being navigated:
Upvotes: 8