【问题标题】:WKWebView is not working with JavaScript ClassesWKWebView 不适用于 JavaScript 类
【发布时间】:2018-12-05 22:55:08
【问题描述】:

我正在使用 WKWebView 开发一个项目,并且我从本地项目加载了 html。 JavaScript 按预期工作,但是当我尝试使用一个类时,它会使 WebView 显示为空白。

我尝试过使用 ES6 语法和 ES5 语法,它们都会导致相同的问题。有没有办法在 WKWebView 的本地 html 文件中使用 JavaScript 类?如果有我做错了什么?

这是我的 WebView 应用程序代码

import UIKit
import WebKit

class ViewController: UIViewController {

let webView = WKWebView()
let remoteAccess = false
let url = "Website/index"

override func loadView(){

    if(remoteAccess){
        loadWebView(string: url)
    }else{
        loadLocalWebView(string: url)
    }

    self.view = webView
}

override var prefersStatusBarHidden: Bool{
    return true;
}

override func viewDidLoad() {
    super.viewDidLoad()

}

func loadWebView(string: String){
    if let url = URL(string: string){
        let request = URLRequest(url: url);
        webView.load(request)
    }else{
        print("Failed to connect to URL: " + string)
    }
}

func loadLocalWebView(string: String){
    if let url = Bundle.main.url(forResource: string, withExtension: "html"){
        webView.loadFileURL(url, allowingReadAccessTo: url.deletingLastPathComponent())
    }else{
        print(string + "not found!")
    }

}
}

这是html文件的代码

<!DOCTYPE html>
<html>
    <head>
        <title>Local Demo</title>
        <meta name="viewport" 
content="width=device-width, initial-scale=1">
        <link rel="stylesheet" type="text/css" 
href="index.css" />
    </head>
<body>
    <script>

        var display = new Display(window.innerWidth,window.innerHeight);
        var ctx = display.create();
        function render(){
            ctx.fillRect(0,0,100,100);
            requestAnimationFrame(render);
        }
        render();

        function Display(width,height){
            this.canvas = document.createElement("canvas");
            this.canvas.id = "canvas";
            this.canvas.width = width;
            this.canvas.height = height;
        }

        Display.prototype.create = function(){
            document.body.appendChild(this.canvas);
            this.ctx = canvas.getContext("2d");
            return this.ctx;
        }
    </script>
</body>

【问题讨论】:

  • return ctx; in Display.prototype.create 函数应该是return this.ctx;
  • @amn 你的权利,我已经解决了,但它并没有解决问题

标签: javascript swift html oop wkwebview


【解决方案1】:

原来的问题,是我在创建实例后定义类,这导致没有任何工作,在翻转顺序后,一切正常。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-14
    • 1970-01-01
    • 2015-09-14
    • 1970-01-01
    • 2017-04-14
    相关资源
    最近更新 更多