简体   繁体   中英

Swift on OSX: WebView stringByEvaluatingJavaScriptFromString doesn't work

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

About myWebView.windowScriptObject.evaluateWebScript("alert('test'‌);"); , you should also do this webView(_:runJavaScriptAlertPanelWithMessage:initiatedBy:) , and then you can print the message , you will get the message of the alert. And if you want to pop up a alert box, you need to do it yourself.

Swift 4 WebView is deprecated. Please use WebKit instead.

import WebKit
//---

let webConfiguration = WKWebViewConfiguration()
let preferences = WKPreferences()
preferences.javaScriptEnabled = true

webConfiguration.preferences = preferences

webView = WKWebView(frame: .zero, configuration: webConfiguration)
webView.translatesAutoresizingMaskIntoConstraints = false

self.webView.evaluateJavaScript("document.getElementById('name').value='\(self.nameTextField.text)';", completionHandler:{ [weak self] _, error in
    DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
        if error != nil {
            // Do something
            return
        }
    }
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM