Handling alert or confirm windows

From Chickenfoot Script Repository


// ==UserScript==
// @name Handling alert or confirm windows

// This script creates and closes an alert dialog.
// You can use the same technique to close security dialogues, etc.

// create, and close, an alert.
handleDialog();
alert('hi');

// function that tries for exactly two seconds to "handle" a dialog  (like an alert).
function handleDialog() {
  setTimeout(closeWindow, 500);
  setTimeout(closeWindow, 1000);
  setTimeout(closeWindow, 1500);
  setTimeout(closeWindow, 2000);
}

// use this function, instead of click, if you want to handle an alert.
function myclick(pattern) {
  handleDialog();
  click(pattern);
}

// Close the current window, if it isn't the main window of the screen.
function closeWindow() {
  // get the most recent window
  var win = Components.
            classes["@mozilla.org/appshell/window-mediator;1"].
            getService(Components.interfaces.nsIWindowMediator).
            getMostRecentWindow(null);

  if (win == chromeWindow) { 
    output('----'); 
    return; 
  }
  
  // get the title of the most recent window
  // you probably want to only close windows of certain titles.
  output('Window Title: ' + win.title);

  output('close the window.');
  
  // close the window
  try {
    win.doOK()
  }catch (e) {
    win.close();
  }
}