Adding Javascript to WKWebView

自作多情 提交于 2020-12-12 07:30:13

问题


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

回答1:


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



来源:https://stackoverflow.com/questions/50199672/adding-javascript-to-wkwebview

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!