![](/img/trans.png)
[英]Get Response of another javascript function in a javascript function
[英]Get Javascript function response in iOS using Swift
我試圖弄清楚如何使用swift平台在我的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中指定的操作
你能幫我一下嗎。
任何幫助都將深表感謝。
如果您使用的是WKWebView
,則可以使用
webView.evaluateJavaScript("YourJavaScript",completionHandler : nil )
對於UIWebView
您可以使用
webview.stringByEvaluatingJavascriptFromString : @"YourJavaScript";
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.
}
}
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.