问题
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)
}
}
回答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&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