WKWebView调用js
直接调用js的changeHead()
方法:
webView.evaluateJavaScript("changeHead()") { (any, error) in
if (error != nil) {
print(error)
}else{
print(any)
}
}
webView.evaluateJavaScript("alert('webview加载完成')", completionHandler: nil)
js调用App,传递参数等
WKWebView初始化时候配置WKWebViewConfiguration
参数,方法注入可以是多个:
let webConfig = WKWebViewConfiguration()
webConfig.userContentController = WKUserContentController()
webConfig.userContentController.add(self , name: "Native")
webConfig.userContentController.add(self , name: "callbackHandle")
webConfig.userContentController.add(self , name: "callbackHandle2")
let wkwebView = WKWebView.init(frame: self.view.frame, configuration: webConfig)
self.view.addSubview(wkwebView);
self.wkwebView = wkwebView
let htmlPath = Bundle.main.path(forResource: "wkWebPage", ofType: "html", inDirectory: "jsCoreDir");
wkwebView.uiDelegate = self
wkwebView.load(URLRequest.init(url: URL.init(fileURLWithPath: htmlPath!)))
对应WKScriptMessageHandler
需要实现的方法,对应app事件的响应:
extension WKSwiftCallJS_Controller:WKScriptMessageHandler{
func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
print(message.name)
switch message.name {
case "Native":
print(message.body)
break;
case "callbackHandle":
print(message.body)
case "callbackHandle2":
print(message.body)
break;
default:
break
}
}
}
js调用的方法为:
<script>
function callNativeApp(){
try{
webkit.messageHandlers.callbackHandle.postMessage("Hello World")
}catch(error){
console.error('The native context not exist ')
}
}
function callNativeApp2(){
try{
webkit.messageHandlers.callbackHandle2.postMessage({key: "Hello", value: "World"})
}catch(error){
console.error('The native context not exist ')
}
}
function changeHead(){
document.querySelector('h1').style.color = "red"
}
</script>
此外,为了保证iOS、Android兼容性,推荐使用狐神的做法http://www.skyfox.org/javascript-ios-navive-message.html
<script type="text/javascript">
function callMobile(handlerInterface,handlerMethod,parameters){
var dic = {'handlerInterface':handlerInterface,'function':handlerMethod,'parameters': parameters};
if (/(iPhone|iPad|iPod|iOS)/i.test(navigator.userAgent)){
window.webkit.messageHandlers[handlerInterface].postMessage(dic);
}else{
window[handlerInterface][handlerMethod](JSON.stringify(dic));
}
}
function callMobileNative(handlerMethod,parameters){
callMobile("Native",handlerMethod,parameters);
}
</script>