Question

I have done something like this a long time ago where I captured the alerts and prevented the default browser based alert box from popping up and replaced it with a modal of one kind or another. However its been so long since I have done that, and I can't find any reference from old code of mine how I did it, nor can I find anything relevant via google currently. So.. I am hoping someone here can aid me in this and help me out. I havent tried anything yet so save yourself the question of what did I try. Other than spending the last hour or so googling different phrases for any snipplet of code that resembles whats in my blurry memory I've come up empty handed. I know, this is kind of a poor quality question to, but at the same time I am sure others would appreciate knowing the answer as well.

All I want to do in my case is capture the event that would trigger the alert() box and pass the message that was in it to another variation of notification. Currently I am doing some work in appmobi with a couple others and I want to take alert() capture it then use

AppMobi.notification.alert(message,title,buttontext); as the default action for alert()

Was it helpful?

Solution

You can simply overwrite the alert method:

window.alert = function(msg) {
   // whatever you want to do with 'msg' here
};

Note that this won't have the blocking behavior of a regular alert

OTHER TIPS

window.alert = function(message,title,buttontext) {
   AppMobi.notification.alert(message,title,buttontext); 
};

As others have pointed out, it can be overridden - just remember that AppMobi.notification.alert expects three arguments. I would not be surprised if it has fallback defaults, but better safe than sorry:

//alert is a native code function that we may need elsewhere
window.legacyAlert = window.alert;
window.alert = function(_msg) {
  AppMobi.notification.alert(_msg, 'Alert', 'OK');//or whatever
};

This overrides the method globally. Alternatively you may require for it to be overridden only in some parts of your code using closures:

alert('this is a vanilla js alert');
(function(alert) {
    alert('this alert has been overridden');
})(AppMobi.notification.alert);
alert('this is another vanilla js alert');

Fiddled

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top