将Javascript添加到WKWebView

时间:2018-05-06 12:25:23

标签: ios swift wkwebview

嗨,我知道这似乎是一个非常简单的问题,但我想将这个JS添加到我的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>

现在很明显我知道这是HTML,但我不知道该怎样投入&#39; evaluateJavaScript&#39;为了使用JS源代码。很抱歉,如果这不是很清楚 - 我对Swift和JS都不熟悉。谢谢!

我的快捷代码:

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 个答案:

答案 0 :(得分:1)

使用内置API WKUserScript注入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:一个布尔值,指示脚本是仅应注入主框架还是注入所有框架(包括iframe)。