Search code examples
rubyfirefoxrspecwatirfirewatir

In Firewatir, how can I interact with the Firefox print dialog?


I'm trying to test a page that has the print dialog appear immediately upon accessing it. All I need to do is close the dialog or click Cancel on it so I can interact with the page behind it. I've tried to figure out how to do this, but everything I've found indicates that it isn't possible in Firefox.


Solution

  • If you're on MacOS or Linux, not sure what to tell you...I bet it's possible, but I need to learn how myself. :)

    If you're on Windows, I do have some suggestions. I suggest checking out the RAutomation gem, which is good for tasks like this (locating and clicking Cancel in the Firefox Print dialog):

    https://github.com/jarmo/RAutomation

    Or you can try using AutoIt. Installing Watir also installs a copy of AutoItX3.dll, which you can use for simple GUI automation like this.

    To see if AutoIt is ready to use on your system, try this out in irb - this code will wait 10 seconds for the Firefox Print dialog to appear, then click the Cancel button:

    irb(main):001:0> require 'win32ole'
    => true
    irb(main):002:0> autoit = WIN32OLE.new('AutoItX3.Control')
    => #<WIN32OLE:0x3c61ce0>
    irb(main):003:0> result = autoit.WinWaitActive('Print', '', 10)
    => 1
    irb(main):004:0> result = autoit.ControlClick('Print', '', 'Cancel')
    => 1
    

    If the "WIN32OLE.new('AutoItX3.Control')" line raises an exception, you may need to use regsvr32.exe to register the DLL. For example, here's how to do that on Win7:

    • Start an elevated cmd.exe

    • regsvr32 C:\Ruby187\lib\ruby\gems\1.8\gems\watir-1.6.5\lib\watir\AutoItX3.dll

    (Note that you might need to change the path above if your Ruby installation is not in C:\Ruby187 or you have a different Watir version than 1.6.5.)

    AutoIt documentation is here:

    http://www.autoitscript.com/autoit3/docs/

    One last thing to watch out for:

    If the statement in your code that brings up the Print dialog blocks until the dialog is closed, things get a little more complex. You'll need to use threads or an external process to handle the dialog (since I don't think FireWatir has a click_no_wait method yet).