In the first part of the scriptable tutorial, we read out the data of a URL using a scriptable request:
let req = new Request(url);
let html = await req.loadString();
The request provides the raw data of the transferred URL in a fast and effective way. However, the .loadString method does not interpret the data received. In particular, no scripts contained in the response are executed. Dynamic websites that read parts of the website via script are therefore only returned incompletely.
The WebView class helps us here. This uses the Safari rendering engine to load the requested URL completely and to execute any dynamic components it may contain. The example for loading a URL using WebView then looks like this:
let view = new WebView();
await view.loadURL(url);
let html = await view.getHTML();
The code is actually very similar to using the request class, but provides an interpreted result depending on the URL used. In the variable html there is now all the data that could be read through scripts.
Performance
A disadvantage of using WebView should be pointed out at this point: In principle, a browser is loaded in the background, which significantly slows down the execution. If you adapt the example to Tutorial 1 and use the WebView class instead of the request, you will notice a delay of a few seconds in the widget before the widget’s data is displayed. Depending on the website, the Java scripts contained in the response are then executed on top.
Further possibilities through WebView
In addition to reading requests, there is also the option of displaying a website directly using WebView.
To do this, the static method loadHTML should be used instead of loadURL:
WebView.loadURL("https://www.google.de")
Safari opens as a popup dialog and shows google. Via two optional parameters the size of the popup can be adjusted or the popup can be opened fullscreen.
If you have an HTML file available locally as a file and want to display it, this is also easily possible using the loadFile method:
let fm = FileManager.iCloud()
let dir = fm.documentsDirectory()
let fileName = "html/index.html"
let path = fm.joinPath(dir, fileName)
WebView.loadFile(path, new Size(0, 300))
Conclusion
The WebView class enables websites to be loaded completely with very little effort and, if necessary, to be displayed. If only static raw data is needed, the Request class is better suited due to the better performance.
Finally, as always, the reference to
Hundreds of examples can be found here just waiting to be tried. You will also be happy to help with problems here.
If you like my little scriptable tutorial, I would be happy about a small tip:
https://www.paypal.com/paypalme/markmescher/2,99
You are of course free to decide how big the coffee should be 🙂
If you have any suggestions for this tutorial, I look forward to your comments!