Executing webKit javascript commands from Scriptable

Hi,

I’m trying to load a YouTube video then use two javascript commands to act on the page:

  1. Force the video fullscreen.

  2. Play the video.

Here is the code I’m using now:

  var url = "https://www.youtube.com/embed/Gz-jBbuqHZg?start=100"
  
  var type = "video";
  
  var view = new WebView;
  
  let jsCode = `
  
     document.getElementsByClassName('ytp-play-button')[0].click();
    
     document.querySelector("video").webkitEnterFullScreen();
  
  `
  
  // load the url into the webview
  view.loadURL(url);
  console.log("loading the page");
  
  // wait for the page to load
  view.waitForLoad();
  console.log("page loaded");
  
  // show the page fullscreen
  view.present(true);
  console.log("showing the page");
  
  // maximize the video, hide the chrome and play the video
  view.evaluateJavaScript(jsCode);

Things go as planned, but the JS code does not do anything. If I use these same commands as bookmarklets they work just fine. I know this is a stupid mistake. Please point out the error of my ways.

Well… looks like I solved my own problem and as expected it was a series of stupid little things. Here is the code snippet that works:

  var url = args.shortcutParameter;
  
  var view = new WebView;
  
  let jsCode = `
  
     function playVideo() {
  
        setTimeout(function() {
           document.querySelector("video").webkitEnterFullScreen();
        }, 1000);
     
        document.getElementsByClassName('ytp-play-button')[0].click();

     }
    
    playVideo();
  
  `
  
  // load the url into the webview
  await view.loadURL(url);
  
  // maximize the video, hide the chrome and play the video
  view.evaluateJavaScript(jsCode);
  
  // show the page fullscreen
  view.present(true);
  
  Script.complete();

Note the need to manually wait for one second before we can successfully execute Javascript commands on the document.

Scriptable rocks!

1 Like