使用 UIWebview 使用 javascript 调用 swift 函数
Call swift function with javascript using UIWebview
如果有人问我,我深表歉意,但我找不到任何答案或解决方案。我希望从 "UIWebView" 调用 JavaScript 函数并在 swift 中监听它。我发现的任何示例都使用 "WKWebView"。必须有一种简单的方法来收听如下所示的 JavaScript 函数:
// HTML / JS
<div id ="myDiv" onclick="listenInSwift()">myItem</div>
这可以用 UIWebView 实现吗?谢谢大家!
像这样实施listenInSwift
:
function listenInSwift() {
window.location = 'yoururlscheme://somehost?greeting=hello'
}
然后在您的 UIWebViewDelegate
class:
中使用此代码收听此 URL
func webView(_ webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType navigationType: UIWebViewNavigationType) -> Bool {
if request.URL.scheme == 'yoururlscheme' {
print('Hello JavaScript...')
}
}
不要忘记在 Xcode.
中注册您的 URL 方案(在本例中为 '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)
这对我来说效果很好:
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
}
注意:您必须在 xcode 项目设置中添加 "com.example.app" 或其他内容。转到信息,向下滚动并找到 URL Scheme。在那里添加您想要的方案。其他东西保持原样。那么它应该可以正常工作。
如果有人问我,我深表歉意,但我找不到任何答案或解决方案。我希望从 "UIWebView" 调用 JavaScript 函数并在 swift 中监听它。我发现的任何示例都使用 "WKWebView"。必须有一种简单的方法来收听如下所示的 JavaScript 函数:
// HTML / JS
<div id ="myDiv" onclick="listenInSwift()">myItem</div>
这可以用 UIWebView 实现吗?谢谢大家!
像这样实施listenInSwift
:
function listenInSwift() {
window.location = 'yoururlscheme://somehost?greeting=hello'
}
然后在您的 UIWebViewDelegate
class:
func webView(_ webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType navigationType: UIWebViewNavigationType) -> Bool {
if request.URL.scheme == 'yoururlscheme' {
print('Hello JavaScript...')
}
}
不要忘记在 Xcode.
中注册您的 URL 方案(在本例中为 '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)
这对我来说效果很好:
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
}
注意:您必须在 xcode 项目设置中添加 "com.example.app" 或其他内容。转到信息,向下滚动并找到 URL Scheme。在那里添加您想要的方案。其他东西保持原样。那么它应该可以正常工作。