1

我试图弄清楚如何使用 swift platform 在我的 iOS 应用程序中实现 JavaScript 函数

我已经尝试了链接中指定的示例代码

https://tetontech.wordpress.com/2014/07/15/swift-to-javascript-and-javascript-to-swift-a-round-trip/

但我想要的方式android与链接 http://android-er.blogspot.in/2011/10/call-javascript-inside-webview-from.html中指定的方式相同

你能帮帮我吗?

任何帮助都会深深感激。

4

3 回答 3

4

如果您正在使用WKWebView,您可以使用调用 javascript

webView.evaluateJavaScript("YourJavaScript",completionHandler : nil )

因为UIWebView你可以使用

  webview.stringByEvaluatingJavascriptFromString : @"YourJavaScript";
于 2016-02-26T13:52:53.427 回答
1

这两个链接(第一第二)帮助我解决了我的问题。

html/javascript 代码:

function bar(qq){
    document.getElementById('foo').innerHTML = qq;
}

<div id="foo"></div>

我的 ViewController 看起来像这样:

class ViewController: UIViewController, WKNavigationDelegate, WKUIDelegate {

    var webView: WKWebView

    required init(coder aDecoder: NSCoder) {
        self.webView = WKWebView(frame: CGRect.zero)
        super.init(coder: aDecoder)!
    }

    override func loadView() {
        super.loadView()

        let userContentController = WKUserContentController()

        let source = "bar('Hello from swift');"
        let userScript = WKUserScript(source: source, injectionTime: WKUserScriptInjectionTime.atDocumentEnd, forMainFrameOnly: true)
        userContentController.addUserScript(userScript)

        let configuration = WKWebViewConfiguration()
        configuration.userContentController = userContentController
        self.webView = WKWebView(frame: self.view.frame, configuration: configuration)
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.

        view.addSubview(webView)

        webView.translatesAutoresizingMaskIntoConstraints = false
        let height = NSLayoutConstraint(item: webView, attribute: .height, relatedBy: .equal, toItem: view, attribute: .height, multiplier: 1, constant: 0)
        let width = NSLayoutConstraint(item: webView, attribute: .width, relatedBy: .equal, toItem: view, attribute: .width, multiplier: 1, constant: 0)
        view.addConstraints([height, width])

        let path = Bundle.main.path(forResource: "foldername/index", ofType: "html")!
        let url = URL(fileURLWithPath: path)

        webView.load(URLRequest(url: url))
        webView.allowsBackForwardNavigationGestures = true
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
}
于 2016-10-03T12:06:04.783 回答
0
var AppiwebScript = function() {//in some_file.js
   //TO DO
};

//below is code for xcode
let jScript = "AppiwebScript();"//name js function, in js file
let str_val =  mainWebView.stringByEvaluatingJavaScript(from: jScript)//handeleng js function
于 2016-11-29T09:44:03.227 回答