swift how to execute javascript after anjular have

2019-06-10 02:55发布

问题:

In my ios app, I used WKWebview.evaluateJavaScript() to execute javascript to get a div boundingRect. In my webpage, I used anjularjs to render part of my page, the page contents is as,

  <body ng-app="home" ng-controller="HomeController" style="min-height:700px;">
    <printerinfo></printerinfo>
  </body>
  <div id="movie" style="border: 1px grey dotted; width: 120px; height: 90px;"></div>

swift

func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
    self.wk.evaluateJavaScript("var rect = document.getElementById('movie').getBoundingClientRect(); [rect.x, rect.y, rect.width, rect.height, rect.top, rect.right, rect.bottom, rect.left];") { (result, error) -> Void in
        print(result)
    }
}

From the result,

Optional(<__NSArrayM 0x170251010>(
<null>,
<null>,
120,
90,
0,
120,
90,
0
)
)

The boundingRect is at the origin of the viewport, it seems the body takes no space in the viewport. I thought it's because when the webpage loaded, angualrjs hasn't rendered the body part.

So how can I execute javascript after anjularjs have rendered the page with swift3?

Thank you very much.

回答1:

And I think use native swift or objective-c to detect when the page is loaded is a bad choice. The more flexable and effective way is to use javascript to call the native swift code when page finishing loading. What's more this also work for a specific dom finishing loading event and very dynamic content.

For detail refer to this post.