xcode 在 Webview iOS 中注入 JavaScript 代码

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26573528/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 06:00:38  来源:igfitidea点击:

Inject a JavaScript code in Webview iOS

javascriptiphonexcodeswiftios8

提问by user1731468

I created a iOS web browser with swift language code. And add an extra button to inject a script on that web page, but it always crash when I try this:

我用 swift 语言代码创建了一个 iOS 网络浏览器。并添加一个额外的按钮以在该网页上注入脚本,但是当我尝试这样做时它总是崩溃:

webView!.evaluateJavaScript("document.body.style.background = 'red';", nil)

Any idea how to fix this? And how to read the JavaScript code from a file, and then inject it to that webview element.

知道如何解决这个问题吗?以及如何从文件中读取 JavaScript 代码,然后将其注入该 webview 元素。

I use the code style as this example but with WKWebView: https://github.com/rshankras/WebViewDemo

我使用代码风格作为这个例子,但使用WKWebViewhttps: //github.com/rshankras/WebViewDemo

If you can solve this question I need a basic working code in the answer. And solution for how to load the JavaScript from a file. And inject that code in the WKWebView element.

如果你能解决这个问题,我需要在答案中提供一个基本的工作代码。以及如何从文件加载 JavaScript 的解决方案。并在 WKWebView 元素中注入该代码。

回答by mattr

I don't see the method you are using (evaluateJavaScript) in the current UIWebView API docsbut it is in the WKWebView docs. Maybe you are using the wrong API? Perhaps try using stringByEvaluatingJavaScriptFromString(_:)instead:

我在当前的UIWebView API 文档中没有看到您正在使用的方法 (evaluateJavaScript),但它在WKWebView 文档中。也许您使用了错误的 API?也许尝试使用 stringByEvaluatingJavaScriptFromString(_:)代替:

let script = "document.body.style.background = 'red'"
if let result = webView.stringByEvaluatingJavaScriptFromString(script) {
    println("result is \(result)")
}

Also, i'm not sure if the "!" is needed (a hunch tells me it's not), as there is no context around your code. So maybe try both versions.

另外,我不确定“!” 是需要的(直觉告诉我不是),因为您的代码没有上下文。所以也许尝试两个版本。

Getting a string from a file is something like:

从文件中获取字符串类似于:

let path = NSBundle.mainBundle().pathForResource("jsFileName", ofType: "js")
if let content = String.stringWithContentsOfFile(path, encoding: NSUTF8StringEncoding, error: nil) {
    println("js content is \(content)")
}

Loading from disk has a lot of variables around how your file is being copied and stored so your going to have to do some work to fit the pathvariable to your structure.

从磁盘加载有很多关于如何复制和存储文件的变量,因此您必须做一些工作以使path变量适合您的结构。

回答by bpolat

This will work with WKWebView. Dont forget to add WebKit frame work on top on your class definition

这将适用于 WKWebView。不要忘记在类定义的顶部添加 WebKit 框架工作

      var webView: WKWebView!

 func loadWebViewWithCustomJavaScript {
    //Create Preferences 
    let preferences = WKPreferences()
    preferences.javaScriptEnabled = true
    //Initialise javascript file with user content controller and configuration
    let configuration = WKWebViewConfiguration()
    let scriptURL =    NSBundle.mainBundle().pathForResource("Your File Name", ofType: "js")
    var scriptContent = ""
    do {
        scriptContent = try String(contentsOfFile: scriptURL!, encoding: NSUTF8StringEncoding)
    } catch{
    print("Cannot Load File")
   }
    let script = WKUserScript(source: scriptContent, injectionTime: .AtDocumentStart, forMainFrameOnly: true)
    configuration.userContentController.addUserScript(script)
    configuration.preferences = preferences
    //Create WebView instance
    webView = WKWebView(frame: CGRectMake(0,0, self.view.frame.size.width, self.view.frame.size.height), configuration: configuration)
    view.addSubview(webView)
    //Finally load the url
    let url = NSURL(string:"your URL")
    let urlRequest = NSURLRequest(URL: url!)
    webView.loadRequest(urlRequest)
  }

Sample JavaScript code for injection

用于注入的示例 JavaScript 代码

 //Hides name of "background1" element on the page
 var styleTag = document.createElement("style");
 styleTag.textContent = 'div#background1, .after-post.widget-area      {display:none;}';
document.documentElement.appendChild(styleTag);

回答by ankit9j

Got it working using following. Used String instead of NSString to use native swift 2. Javascript code to inject must be in hidesections.js file

使用以下方法让它工作。使用 String 而不是 NSString 来使用原生 swift 2. 注入的 Javascript 代码必须在 hidesections.js 文件中

    let jsPath = NSBundle.mainBundle().pathForResource("hidesections", ofType: "js");
    let jsContent: String?
    do
    {
        jsContent = try String(contentsOfFile: jsPath!, encoding: NSUTF8StringEncoding)
    }
    catch _
    {
        jsContent = nil
    }
    webView.stringByEvaluatingJavaScriptFromString(jsContent!)

回答by mustafa

If you are using WKWebViewhere is a solution.

如果您使用WKWebView这里是一个解决方案。

if let scriptFile = NSBundle.mainBundle().pathForResource("script", ofType: "js") {
    var error: NSError?
    let scriptString = NSString(contentsOfFile: scriptFile, encoding: NSUTF8StringEncoding, error: &error)
    if let error = error {
        println("Error: Could not load script file => \(error)")
    } else {
        if let scriptString = scriptString {
            let script = WKUserScript(source: scriptString, injectionTime: .AtDocumentEnd, forMainFrameOnly: true)
            let controller = WKUserContentController()
            controller.addUserScript(script)

            let configuration = WKWebViewConfiguration()
            configuration.userContentController = controller

            let webView = WKWebView(frame: self.view.bounds, configuration: configuration)
            self.webView = webView
            self.view.addSubview(webView)
        }
    }
}