Capturing Javascript Alert in Webbrowser Control
-
05-07-2019 - |
Question
Using the webbrowswer control to cruise a site. Sometimes errors occur which involve a javascript popup box. I would like to do a couple of things when this happens.
- Know when a javascript alert popups up.
I have used the LostFocus event with some success but anytime it losses focus that code runs which is annoying.
- I would like to know the exact text that the alert box says.
I am not sure where to find the alert box object or cast it for use in C#. I looked all over the internet and couldn't find it.
Any one any clue?
Solution
If you're looking to only trap script error dialogs that appear, I would recommend trapping the window.onerror DOM event. If you assign a handler for this event, the message, (script) file name and line number are passed as arguments, those are all things shown in the error dialog that pops up. Note that most users have scripting error dialogs switched off by default so it would be wise to honour this if the intended purpose is for a large audience.
I'm not sure if there's an easier way, I've only worked with the old COM WebBrowser component.
OTHER TIPS
Just do this:
window.alert = function(txt) {
// Do something
}
This will allow you to do a callback or anything else you want with the alert text.