Hi I know this seems like a super simple question, but I want to add this JS to my WebView:
<script type='text/javascript' src='https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.2/MathJax.js?config=default&ver=1.3.8'></script>
Now obviously I know this is HTML, but I am not sure what to put into 'evaluateJavaScript' in order to use the JS source. Sorry if this isn't very clear - I'm new to both Swift and JS. Thanks!
My swift code:
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
self.webView.evaluateJavaScript("<script type='text/javascript' src='https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.2/MathJax.js?config=default&ver=1.3.8'></script>") { (nil, error) in
print(error)
}
}
Load Local HTML File to a WKWebViewlet myUrl = myProjectBundle. url(forResource: "my-html-file", withExtension: "html")!
You can implement WKWebView in Objective-C, here is simple example to initiate a WKWebView : WKWebViewConfiguration *theConfiguration = [[WKWebViewConfiguration alloc] init]; WKWebView *webView = [[WKWebView alloc] initWithFrame:self. view. frame configuration:theConfiguration]; webView.
The WKWebView is a modern API applying all the modern web security mechanisms, it's still maintained by Apple and gets updates. The good thing about WKWebView is that it does out-of-process rendering, so if the attackers find a memory corruption vulnerability in it, your application's process is still isolated.
Use built-in API WKUserScript
inject JS:
let script = """
var script = document.createElement('script');
script.src = 'https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.2/MathJax.js?config=default&ver=1.3.8';
script.type = 'text/javascript';
document.getElementsByTagName('head')[0].appendChild(script);
"""
let userScript = WKUserScript(source: script, injectionTime: .atDocumentStart, forMainFrameOnly: true)
let contentController = WKUserContentController()
contentController.addUserScript(userScript)
let webViewConfiguration = WKWebViewConfiguration()
webViewConfiguration.userContentController = contentController
let webView = WKWebView(frame: CGRect.zero, configuration: webViewConfiguration)
forMainFrameOnly: A Boolean value indicating whether the script should be injected only into the main frame or into all frames(including iframe).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With