That's my first question here after years as a web developer now trying to code an OSX App using Xcode and Swift (latest).
What I'm trying to do is to execute JavaScript on the Webpage I'm loading with Webkit/WebView. I tried so many ways (the internet is full of answers - mostly for iOS) but there is quite little for OSX + Swift + WebView (not UIWebview or WkWebView).
My latest approach is this ViewController.swift:
import Cocoa
import WebKit
class ViewController: NSViewController, WebFrameLoadDelegate {
var myWebView:WebView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
myWebView = WebView(frame: self.view.frame)
myWebView.frameLoadDelegate = self
//Load URL
let url = NSURL(string: "http://google.com");
let request = NSURLRequest(URL: url!);
myWebView.mainFrame.loadRequest(request)
self.view.addSubview(myWebView)
//Insert JS
myWebView.stringByEvaluatingJavaScriptFromString("alert('test');");
let script = "document";
if let returnedString = myWebView.stringByEvaluatingJavaScriptFromString(script) {
print("the result is \(returnedString)");
}
}
/*
* Page ready
*/
func webViewDidFinishLoad(myWebView : WebView) {
print("WvFinished")
}
func webViewDidStartLoad(myWebView : WebView) {
print("WvStarted")
}
}
Neither the JS-Alert nor the return of the html document works.
PS: Neither the "webViewDidFinishLoad" nor the "webViewDidStartLoad" seems to be executed.
I would really appreciate any help. I guess I've almost searched the whole web for all hints - but nothing worked for me.
Thank you in advance!
Best,
Alex
func webView(sender: WebView!, didFinishLoadForFrame frame: WebFrame!) { print("didFinishLoadForFrame") }
– Leo DabusmyWebView.windowScriptObject.evaluateWebScript("alert('test');");
, but same as always: No JS-Alert at all. Did you mean to use it that way? Best! – AlexDoe