Is there a way to simulate a click on an alert in JavaScript?
Asked Answered
A

6

12

I have a page with an iframe whose source page is in a separate domain. From time to time, the source page generates an alert. When it does so, it stops what it is doing until the user clicks OK to the alert.

What I would like to do is programmatically click OK on this alert so the source page can get back to being useful. Is this possible?

Asa answered 19/2, 2009 at 3:52 Comment(0)
S
21

JavaScript is single-threaded, which means when you call a function, it blocks until it returns. When you call alert(), that passes control to the browser which decides how to handle it. It is not Javascript which is popping the UI dialog, it is the browser. alert() does not return until the browser receives the "OK" event and returns control. The javascript thread is halted until that happens.

So for at least two different reasons stated in the above paragraph, the answer is no :)

Schwing answered 19/2, 2009 at 4:1 Comment(2)
Confirmed my suspicions. I will need to use something in addition to or instead of JavaScript for this one.Asa
JavaScript thread is not halted, the messages are still pumped and any timers or async changes will still fire event handlers, and JS in those handlers will still run.Impower
D
9

I'm pretty sure it's not possible.

Discovery answered 19/2, 2009 at 3:56 Comment(2)
@Whoever's downvoting this: take a look at the question, which is a straight-up yes-no, possible or not-possible. The other answers are better, but a down-vote for being the first to answer the question correctly? Weird.Discovery
+1 for being technically correct. My question was yes/no and the yes/no was whether I could do it entirely in JavaScript.Asa
P
5

What happens if you override alert with a no-op in your code?

e.g.

<script>
// uncomment next line to swallow alerts
//  function alert(nope) { return; }
<script>
<script>
  $(document).ready(function() { alert("Hello, world!"); });
</script>

With the line commented out, alert appears. With line commented in, alert does not appear.

Pademelon answered 19/2, 2009 at 4:1 Comment(6)
This is a good alternative, assuming the developer doesn't mind losing alerts across the board.Schwing
Would this work even if the offending code is in an iframe whose source is in a separate domain?Discovery
I have tried this in the parent of the iframe, and it has no effect on the alerts generated by the iframe. It does, however, suppress all alerts generated by the parent of the iframe.Asa
Technically and directly, the answer to the original question posed by the OP is a resounding "No." However, I have tested and examined this idea, and it functions just well. If we place the script within the iFrame's DOM, it ought to function similarly in an iFrame as well. I can give this response a rating of more than 100. One of the nicest responses I received clarified a key JavaScript concept for me. +100Enterotomy
Yes, it has its own glitches, such as the developer losing all of the alerts, but I think this can be worked around if the requuirement is to handle the alert for him.Enterotomy
If you need to remove a specific alert, you can manipulate the condition, if any, where the alert happens.Ursola
T
3

You shouldn't have a problem if you know the text of the alert and don't mind getting dirty.

You can override the iframe window's alert with your own and do something to the effect of..

document.getElementById("InnerFrameName").contentWindow.alert = function(){
    if (arguments[0].toLowerCase() == "innerframe alert text")
        return; //supress
    else
        alert(arguments[0]);
};

Edit: I made a little test with a proxy handler (it's in asp.net/c# but you should get the idea)...

The external page in my test is a w3 page with a button that displays an alert, the alert is now passed through the user defined function.

I'm sure this is alot more dirty then you'd like to get.

Page:

<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Hello From MyPage</title>
    <script type="text/javascript">
        function frameLoaded() {
            document.getElementById("InnerFrameName").contentWindow.alert = function() {
                if (arguments[0].toLowerCase() == "i am an alert box!!") {
                    alert("MESSAGES WOULD BE SUPRESSED: " + arguments[0]);
                    return; //supress
                } else {
                    alert(arguments[0]);
                }
            };
        }
        </script>
</head>
<body onload="alert('Hello from an unsupressed top level frame message!');">
    <form id="form1" runat="server">
            <div>
                <h1>Internal Page (Top Level)</h1>
                <hr />
                <iframe id="InnerFrameName" onload="frameLoaded();" src="PageProxy.ashx?externalURI=http://www.w3schools.com/JS/tryit_view.asp?filename=tryjs_alert"
                    style="width: 800px; height: 600px;">Derp!...</iframe>
            </div>
    </form>
</body>
</html>

Proxy Handler:

<%@ WebHandler Language="C#" Class="PageProxy" %>

using System;
using System.Web;

public class PageProxy : IHttpHandler {

    public void ProcessRequest (HttpContext context) {
            byte[] externalPage = new System.Net.WebClient().DownloadData(context.Request["externalURI"]);
            context.Response.OutputStream.Write(externalPage, 0, externalPage.Length);
            context.Response.End();
    }

    public bool IsReusable {
        get {
            return false;
        }
    }
}
Twostep answered 19/2, 2009 at 5:8 Comment(2)
The iframe source is in an external domain, so permission was denied when I tried this.Asa
Yeah I was afraid domain permissions would cause an issue, only workaround then is creating a local proxy page/handler etc to load the remote page so it's then in-domain and this script should work.Twostep
A
1

I highly doubt it. If by separate domain, do you mean one which you have no control over?

If you do have control, you could change the alerts to modal Javascript boxes, which you could control.

Algie answered 19/2, 2009 at 3:59 Comment(0)
N
0

The best bet to solve your problems with annoying JavaScript would be to override it with a client side scripting tool like Greasemonkey.

Nesbitt answered 19/2, 2009 at 5:6 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.