Need Help:How to execute javascript in the Chrome print preview page f

I am new to Applescript and I am trying to automate the print operation in Chrome using Applescript. I wanted to access the control present in the print preview page but the javascript code is not working. Steps are

  1. Open a website in Chrome like “https://macscripter.net/
  2. Press command+ p
  3. Print preview window appears I am trying to click the print button on that window using Applescript.
    Please find my code snippet below
tell application "Google Chrome" to tell active tab in front window to execute javascript "document.querySelector(\"print-preview-app\").shadowRoot.querySelector(\"print-preview-sidebar\").shadowRoot.querySelector(\"print-preview-destination-settings\").shadowRoot.querySelector(\"print-preview-destination-select\").shadowRoot.querySelector(\"print-preview-settings-section\").querySelector(\"select\").value=\"HP/local/\""

I don’t know anything about javascript (although your code does compile in vivaldi) but you could use key codes to work through that dialogue. I don’t use Chrome but I occasionally use Vivaldi and this works in that. Key code 35 simulates pressing the ‘p’ key, and key code 36 the ‘return’ key.

tell application “Google Chrome”
activate
tell application “System Events”

	key code 35 using command down
	delay 1
	key code 36

end tell

end tell

Of course, it will print with whatever the default settings are. If you really with to only run it from within the print dialogue, then remove the ‘35’ line.

Not really related to your question but you could also automate saving as pdf this way.

Hi, Thanks for your reply but I looking for a solution with the javascript the key sequence might change for different option

Hi,

what you call print preview page is indeed Print dialog of Mac Os X. It is not some webpage, but separate from the browser’s window dialog (sheet). And, you can do javascript only with webpages.

To click “Print” button you should use this dialog’s GUI scripting:


tell application "System Events" to tell application process "Google Chrome"
	click UI element "Print" of sheet 1 of window 1
end tell

Yes you are correct for Safari browser, but I am getting this on Chrome browser where the default print preview window in a webpage