简体   繁体   中英

Retrieve [String] from [object HTMLCollection]

I've been struggling with this. I have a valid javascript command which I send from my wkwebview:

document.getElementById('qlist-wrapper').getElementsByClassName('question-summary narrow').toString();

When I type this from the Safari console I get back

"[object HTMLCollection]"

But when I try to use the returned object, I'm at a loss. I get "EXC_BAD_ACCESS" (Code=1, plus an address). there are 4 payload objects associated with the "html: Any" object; they are all 0s. Here's the code in context:

webView.evaluateJavaScript("document.getElementById('qlist-

wrapper').getElementsByClassName('question-summary narrow').toString();", completionHandler: { (html: Any, error: Error?) in
        print("\(html)")
        if let error = error {
            print("\(error.localizedDescription)")
        }
    })
}

Ultimately my goal is to turn the html collection into an array of Swift strings. How do I do that? I would very much welcome a JSON solution (perhaps using Alamofire), but I simplified my approach to first get something working. (I've worked with Alamofire in the past, but not so much JSON). If I try to look at the variable before printing it, i get:

po html
error: Execution was interrupted, reason: EXC_BAD_ACCESS (code=1, address=0xfffffffffffffff8).
The process has been returned to the state before expression evaluation.

I really have two problems in this question:

1) How do I get an HtmlCollection converted into an Array? and

2) Why am I getting exceptions when I try to work with the results of my javascript call from the WKWebView.

I solved the first piece of this puzzle, so I will document that here and close this. Once I have a better handle on JavaScriptCore (where I expect the ultimate solution lies), I will post a new question and cross reference that question/solution from here.

If I type the following into the Web Inspector Console in Safari, I get desired conversion from HtmlCollection to Array:

Array.prototype.slice.call(document.getElementById('qlist-wrapper').getElementsByClassName('question-summary narrow'));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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