如何在Swift 3中的WKWebView中注入一个javascript

时间:2017-01-25 16:02:37

标签: javascript swift3 wkwebview

我试图通过在整个javascript中注入一个新的CSS规则来排除一些网页元素,如侧边栏,我在xcode中创建了一个新的javascript文件,其中包含一个新的样式标记,以隐藏我在Google Chrome开发人员工具中检查过的边栏并结束使用此代码:

var styleTag = document.createElement("style");
styleTag.textContent = '.sidebar {display:none;}';
document.documentElement.appendChild(styleTag);

并创建了WKWebViewConfiguration对象,该对象包含一些属性,这些属性允许在本地代码和托管Web内容之间创建桥梁,如here所述,但仍然无法运行此脚本。

这是我完整的ViewController代码:

import UIKit
import WebKit

class scrapedBrowser: UIViewController, WKNavigationDelegate {

var webView: WKWebView!
var progressView: UIProgressView!

override func loadView() {

    webView = WKWebView()
    webView.navigationDelegate = self
    view = webView
}

required init?(coder aDecoder: NSCoder) {
    let config = WKWebViewConfiguration()
    let scriptURL = Bundle.main.path(forResource: "hideSections", ofType: "js")
    let scriptContent:String?
    do {
        scriptContent = try String(contentsOfFile: scriptURL!, encoding: String.Encoding.utf8)
    }
    catch _ {
        scriptContent = nil
    }

    let script = WKUserScript(source: scriptContent!, injectionTime: .atDocumentStart, forMainFrameOnly: true)
    config.userContentController.addUserScript(script)
    super.init(coder: aDecoder)
    self.webView?.navigationDelegate = self
}

override func viewDidLoad() {
    super.viewDidLoad()

    let url = URL(string: "http://yourwebsite.com/")!
    let request = URLRequest(url: url)
    webView.load(request)
    webView.allowsBackForwardNavigationGestures = true
}

func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
    title = webView.title
}

}

2 个答案:

答案 0 :(得分:0)

您需要将config分配给WKWebView

webView = WKWebView(frame: CGRect.zero, configuration: config)

答案 1 :(得分:0)

您已在init中创建了配置并添加了脚本,但您尚未保留对配置的引用。稍后在loadView上创建wkwebview而不是之前在init

中创建的配置