9

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)
    }
}
Ahmad F
  • 30,560
  • 17
  • 97
  • 143
Rahul Basi
  • 91
  • 1
  • 1
  • 4

1 Answers1

16

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).

Bannings
  • 10,376
  • 7
  • 44
  • 54
  • This answer works well, however would I be able to do this with a WKWebview created using IB? Thank you for your help – Rahul Basi May 06 '18 at 15:10
  • @RahulBasi It is not possible to set the configuration of the WKWebView through the outlet of WKWebView form the storyboard because the configuration property of the WKWebView is read only. However, if you really want to create WKWebView through xib or storyboard, you have to make a subclass of WKWebView, then instead of calling super initWithCoder, you'll need to use a different init method, such as initWithFrame:configuration:. – Bannings May 07 '18 at 04:04
  • running your code without any changes gives me error like "libMobileGestalt MobileGestalt.c:890: MGIsDeviceOneOfType is not supported on this platform" – Darshan Mothreja Dec 02 '18 at 08:29
  • 8
    While the configuration property is read only, the attached `WKWebViewConfiguration` is mutable. Example: `[self.webView.configuration.userContentController addUserScript:userScript];` – Steven Fisher Jul 22 '19 at 01:22