WKUserScript无法正常运行

时间:2018-07-30 05:04:30

标签: swift webkit ios11 wkwebview javascript-injection

这是我设置WKWebView的配置的方式,

func configWeb() {
        let recentconfig = WKWebViewConfiguration()
        let recentscriptURL = Bundle.main.path(forResource: "getPosts", ofType: "js")
        let recentscriptContent = try! String(contentsOfFile: recentscriptURL!)
        let recentscript = WKUserScript(source: recentscriptContent, injectionTime: .atDocumentEnd, forMainFrameOnly: false)
        let userContentController = WKUserContentController()
        userContentController.add(self as WKScriptMessageHandler, name: "test")
        userContentController.addUserScript(recentscript)
        recentconfig.userContentController = userContentController
        postsWebView = WKWebView(frame: CGRect.zero, configuration: recentconfig)
        postsWebView!.load(URLRequest(url:URL(string:"http://www.appcoda.com")!))
        postsWebView?.navigationDelegate = self
}

我的getPosts.js文件是这样的,

var postsWrapper = document.querySelector('#content')
var posts = postsWrapper.querySelectorAll('.post.type-post.status-publish')
function parsePosts() {
    pos = []
    for (var i = 0; i < posts.length; i++) {
        var post = posts[i];
        var postTitle = post.querySelector('h2.entry-title a').textContent;
        var postURL = post.querySelector('h2.entry-title a').getAttribute('href');
        pos.push({'postTitle' : postTitle, 'postURL' : postURL});
    }
    return pos
}
var postsList = parsePosts();
window.webkit.messageHandlers.test.postMessage(postsList);

此外,不会调用userContentController(_ userContentController:, didReceive:)。我是从AppCoda教程中学到的。我不确定我要去哪里错。这是获取js的方法吗?我已经尝试了一些教程。我没有任何适合我的东西。

因此,userContentController(_ userContentController:, didReceive:)如下,

func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
        print(message.body, message.name)
        if (message.name == MessageHandler) {
            if let postsList = message.body as? [Dictionary<String, Any>] {
                for ps in postsList {
                    let post = Post(dictionary: ps)
                    posts.append(post)
                }
                recentPostsButton.isEnabled = true
            }
        }
    }

0 个答案:

没有答案