如果有人问过我,我很抱歉,但我无法找到任何答案或解决方案。我期待从“UIWebView”调用JavaScript函数并在swift中监听它。我找到的任何例子都使用“WKWebView”。必须有一种简单的方法来收听如下的JavaScript函数:
// HTML / JS
<div id ="myDiv" onclick="listenInSwift()">myItem</div>
这可以通过UIWebView实现吗?谢谢大家!
答案 0 :(得分:12)
像这样实施listenInSwift
:
function listenInSwift() {
window.location = 'yoururlscheme://somehost?greeting=hello'
}
然后在UIWebViewDelegate
课程中使用此代码收听此网址:
func webView(_ webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType navigationType: UIWebViewNavigationType) -> Bool {
if request.URL.scheme == 'yoururlscheme' {
print('Hello JavaScript...')
}
}
不要忘记在Xcode中注册您的URL Scheme(在本例中为'yoururlscheme')。
要在网络视图中加载本地文件,请尝试以下操作:
let baseURL = NSURL.fileURLWithPath(NSBundle.mainBundle().bundlePath);
let relativePath = "www/\(file)"
let fileURL = NSURL(string: relativePath, relativeToURL: baseURL);
let URLRequest = NSURLRequest(URL: fileURL!);
webView.loadRequest(URLRequest)
答案 1 :(得分:0)
这对我来说很好:
func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
if request.url?.scheme == "com.example.app" {
print("I’m some JavaScript hoho")
}
return true
}
注意:您必须添加&#34; com.example.app&#34;或者你的xcode项目设置中的任何内容。转到信息,向下滚动并找到URL Scheme。在那里添加您想要的方案。保持其他东西的方式。然后它应该工作得很好。