I am trying to figure out how to implement JavaScript functions inside my iOS app using swift platform .
I have tried out the example code specified in the link
https://tetontech.wordpress.com/2014/07/15/swift-to-javascript-and-javascript-to-swift-a-round-trip/
But i want in the same way like android
is doing as specified in the link http://android-er.blogspot.in/2011/10/call-javascript-inside-webview-from.html
Could you please help me out.
Any help will deeply appriciated.
If you are using WKWebView
you can call javascript by using
webView.evaluateJavaScript("YourJavaScript",completionHandler : nil )
For UIWebView
you can use
webview.stringByEvaluatingJavascriptFromString : @"YourJavaScript";
These two links (first, second) are helped to me solve my problem.
html/javascript code:
function bar(qq){
document.getElementById('foo').innerHTML = qq;
}
<div id="foo"></div>
My ViewController looks like this:
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.
}
}
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
来源:https://stackoverflow.com/questions/35650931/get-javascript-function-response-in-ios-using-swift