iOS
And are often needed in developmentWKWebview
The most common way to deal with people is with themWKWebview
MediumH5
Interaction between pages,H5
Page is throughJavaScript
andiOS
For interaction, this article exploresJavaScript
andSwift
Interaction between.
H5 page embedding
First, let’s create a new oneHTML
Format and name itindex.html
Its code is as follows:
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<style>
.switch { position: relative; display: inline-block; width: 60px; height: 34px; }
.switch input { opacity: 0; width: 0; height: 0; }
label.switch { outline: none; }
.slider { position: absolute; cursor: pointer; top: 0; left: 0; right: 0; bottom: 0; background-color: #ccc; -webkit-transition: .4s; transition: .4s; outline: none; }
.slider:before { position: absolute; content: ""; height: 26px; width: 26px; left: 4px; bottom: 4px; background-color: white; -webkit-transition: .4s; transition: .4s; }
input:checked + .slider { background-color: #2196F3; }
input:focus + .slider { box-shadow: 0 0 1px #2196F3; }
input:checked + .slider:before { -webkit-transform: translateX(26px); -ms-transform: translateX(26px); transform: translateX(26px); }
.slider.round { border-radius: 34px; }
.slider.round:before { border-radius: 50%; }
</style>
</head>
<body>
<h2>Toggle Switch is off</h2>
<label>
<input type="checkbox" name="myCheckbox">
<span></span>
</label>
</body>
</html>
thisH5
The content of the page is very simple, alabel
And onetoggle switch
, next we areiOS
Monitor in the interfacetoggle switch
Change and synchronize withH5
Interactive updatelabel
Value of.

WKWebview
utilizeWKWebview
Load the created aboveHTML
File:
import UIKit
import WebKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
view.addSubview(webView)
NSLayoutConstraint.activate([
webView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
webView.trailingAnchor.constraint(equalTo: view.trailingAnchor),
webView.bottomAnchor.constraint(equalTo: view.layoutMarginsGuide.bottomAnchor),
webView.topAnchor.constraint(equalTo: view.layoutMarginsGuide.topAnchor)
])
if let url = Bundle.main.url(forResource: "index", withExtension: "html") {
webView.loadFileURL(url, allowingReadAccessTo: url.deletingLastPathComponent())
}
}
private lazy var webView: WKWebView = {
let webView = WKWebView()
webView.translatesAutoresizingMaskIntoConstraints = false
return webView
}()
}
message handel
becauseH5
Page is usedWKWebview
Loaded,WKWebview
Relying onUIViewController
ofSwift
acceptJavaScript
The message is throughWKScriptMessageHandler
This protocol is implemented. This protocol provides a method to acceptJavaScript
So here we letUIViewController
comply withWKScriptMessageHandler
Protocol and implement a necessary method:
extension ViewController: WKScriptMessageHandler{
func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
guard let dict = message.body as? [String : AnyObject] else {
return
}
print(dict)
}
}
Here assumeJavaScript
The message sent isDic
And simply print. The above agreement just makesUIViewController
Unilateral acceptableJavaScript
News, internalWKWebview
I don’t knowUIViewController
The simple understanding of the existence of this role is acceptable
WKWebview
Thousands of news, how do I know it’s youUIViewController?
For this purpose, it is necessary to adoptWKUserContentController
This bridge tellsWKWebview
, there’s oneUIViewController
Preparing to acceptJavaScript
The message sent out is presented here in EnglishWKUserContentController
May be more appropriate:
A WKUserContentController object provides a way for JavaScript to post messages to a web view. The user content controller associated with a web view is specified by its web view configuration.
on topAutoLayout
Add the following after the constraint:
let contentController = self.webView.configuration.userContentController
contentController.add(self, name: "toggleMessageHandler")
JavaScript send message:
Put the following paragraphJavaScript
Put code intoHTML
Document</body>
Above the label:
<script>
var _selector = document.querySelector('input[name=myCheckbox]');
_selector.addEventListener('change', function(event) {
var message = (_selector.checked) ? "Toggle Switch is on" : "Toggle Switch is off";
if (window.webkit && window.webkit.messageHandlers && window.webkit.messageHandlers.toggleMessageHandler) {
window.webkit.messageHandlers.toggleMessageHandler.postMessage({
"message": message
});
}
});
</script>
above
JavaScript
Code whentoggle switch
Open towebkit
send out"Toggle Switch is on"
Message, broadcast when closed"Toggle Switch is off"
News.
After running the project, clickToggle Switch
There will be a corresponding message output on the console after!
Injecting JavaScript
The above example is lucky to have it
HTML
Source code, and it is written insideJavaScript
But there is no interactive code in most cases in actual developmentHTML
Source code, ifSwift
Want to be withHTML
Page interaction can takeInjecting JavaScript
In short, the form ofSwift
Inject a sectionJavaScript
Code toWKWebview
LoadedHTML
The interaction between the two pages.
Comment outindex.html
About in the documentJavaScript
That code, and thenViewController
incontentController.add(self, name: "toggleMessageHandler")
Add the following code below:
let js = """
var _selector = document.querySelector('input[name=myCheckbox]');
_selector.addEventListener('change', function(event) {
var message = (_selector.checked) ? "Toggle Switch is on" : "Toggle Switch is off";
if (window.webkit && window.webkit.messageHandlers && window.webkit.messageHandlers.toggleMessageHandler) {
window.webkit.messageHandlers.toggleMessageHandler.postMessage({
"message": message
});
}
});
"""
let script = WKUserScript(source: js, injectionTime: .atDocumentEnd, forMainFrameOnly: false)
contentController.addUserScript(script)
When running the project, you will find that the printed results are the same as before.
Evaluating JavaScript
adopt
Injecting JavaScript
Can letJavaScript
Send message toSwift
, and throughEvaluating JavaScript
Can letSwift
Send message toJavaScript
。
to updateuserContentController(_: didReceive:)
The codes in are as follows:
guard let message = dict["message"] else {
return
}
let script = "document.getElementById('value').innerText = \"\(message)\""
webView.evaluateJavaScript(script) { (result, error) in
if let result = result {
print("Label is updated with message: \(result)")
} else if let error = error {
print("An error occurred: \(error)")
}
}
First getJavaScript
Send the message and use itscript
To show thatJavaScript
to updateHTML
inlabel
Value of, usingSwift
inWKWebView
ofEvaluating JavaScript
LetJavaScript
Execute this code immediately to achieve the updateHTML
The purpose of the text.

summary
In this article, we have seen how to implement itWKWebView
And the page it loads. Using this, we can use the events on the web page to trigger the actions on the application, and we can also update the loaded web page according to our information on the application.