Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding Javascript to WKWebView

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&#038;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&#038;ver=1.3.8'></script>") { (nil, error) in
        print(error)
    }
}
like image 267
Rahul Basi Avatar asked May 06 '18 12:05

Rahul Basi


People also ask

How do I import an HTML file into WKWebView?

Load Local HTML File to a WKWebViewlet myUrl = myProjectBundle. url(forResource: "my-html-file", withExtension: "html")!

How do I import WKWebView into Objective C?

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.

Is WKWebView secure?

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.


1 Answers

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&#038;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).

like image 183
Bannings Avatar answered Nov 27 '22 02:11

Bannings