Reputation: 97
.
.
.
<script>
function resizeFont(font_index) {
var arrFontSize = ["80%", "90%", "100%", "110%", "120%"];
var x = document.getElementsByTagName("SPAN");
for (var i = 0; i < x.length; i++) {
x[i].style.fontSize = arrFontSize[font_index];
}
}
</script>
The above function is to adjust the font of the page that shows the contents of the book.
override func viewDidLoad() {
super.viewDidLoad()
let webConfiguration = WKWebViewConfiguration()
let contentController = WKUserContentController()
contentController.add(self, name: "resizeFont")
webConfiguration.userContentController = contentController
webView = WKWebView(frame: self.containerView.frame, configuration: webConfiguration)
webView.uiDelegate = self
webView.navigationDelegate = self
self.view.addSubview(ebView)
}
extension SearchWVViewController: WKScriptMessageHandler {
func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
if let name = message.name as? String, name == "resizeFont" {
//code
}
}
The code above executes a function with no parameters to pass. But how do I execute a function while passing a font_index
?
Upvotes: 1
Views: 534
Reputation: 2161
If you want to execute JS function for WKWebView just use evaluateJavaScript
method e.g.
let fontIndex = 1
webView.evaluateJavaScript("resizeFont(\(fontIndex))")
Use userContentController(:)
if you want to receive messages from JS running in a webpage. But in your case, if you want to just execute some JS function in a webpage, you don't need to use WKUserContentController
and WKScriptMessageHandler
, just use evaluateJavaScript
method.
Upvotes: 1