简体   繁体   English

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

[英]How to inject a javascript in WKWebView in Swift 3

I am trying to exclude some webpage elements like sidebar by injecting a new CSS rule throughout javascript, I created a new javascript file in xcode with the a new style tag to hide the sidebar that I inspected in Google chrome developer tool and ended with this code:我试图通过在整个 javascript 中注入新的 CSS 规则来排除一些网页元素,如侧边栏,我在 xcode 中创建了一个新的 javascript 文件,并使用新的样式标签隐藏了我在 Google chrome 开发人员工具中检查的侧边栏,并以此代码结束:

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

and created WKWebViewConfiguration object which holds some properties that allow the creation of the bridge between native code and the hosted web content as described here but still not getting this script running.并创建了 WKWebViewConfiguration 对象,其中包含一些属性,这些属性允许在本机代码和托管的 Web 内容之间创建桥梁,如此处所述但仍无法运行此脚本。

This is my complete ViewController code:这是我完整的 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
}

}

您需要将config分配给WKWebView

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

You have created config and added script to in init and you haven't kept reference of config.您已经在 init 中创建了配置并添加了脚本,但您没有保留对配置的引用。 Later on loadView you are creating wkwebview and not setting configuration you created earlier on in init稍后在 loadView 您创建 wkwebview 而不是设置您之前在 init 中创建的配置

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM