9

我试图通过 UIWebView 的 shouldStartLoadWithRequest 方法将 UIWebView 内的网页中的多个内容传递回我的 iPhone 应用程序。

基本上我的网页调用 window.location.href = "command://foo=bar" 并且我能够在我的应用程序中拦截它没问题。现在,如果我创建一个循环并一次执行多个 window.location.href 调用,那么 shouldStartLoadWithRequest 似乎只被调用一次,并且它获得的调用是在循环结束时最后一次触发 window.location.href 。

Android 的 webview 也会发生同样的事情,只有最后一个 window.location.href 被处理。

4

3 回答 3

41
iFrame = document.createElement("IFRAME");
iFrame.setAttribute("src", "command://foo=bar");
document.body.appendChild(iFrame); 
iFrame.parentNode.removeChild(iFrame);
iFrame = null;

因此,这将创建一个 iframe,将其源设置为我试图传递给应用程序的命令,然后一旦它附加到主体 shouldStartLoadWithRequest 被调用,然后我们从主体中删除 iframe,并将其设置为 null 以释放记忆。

我还使用 shouldOverrideUrlLoading 在 Android webview 上对此进行了测试,它也可以正常工作!

于 2010-05-29T12:24:35.160 回答
3

我也遇到了这个问题,这是适合我的解决方案。我所有的 JavaScript 函数都使用这个函数 __js2oc(msg) 通过 shouldStartLoadWithRequest 将数据和事件传递给 Objective-C:PS 用你使用的“appname:”触发器替换“command:”。

/* iPhone JS2Objective-C bridge interface */
var __js2oc_wait = 300; // min delay between calls in milliseconds
var __prev_t = 0;
function __js2oc(m) {
  // It's a VERY NARROW Bridge so traffic must be throttled
  var __now = new Date();
  var __curr_t = __now.getTime();
  var __diff_t = __curr_t - __prev_t;
  if (__diff_t > __js2oc_wait) {
    __prev_t = __curr_t;
   window.location.href = "command:" + m;
  } else {
    __prev_t = __curr_t + __js2oc_wait - __diff_t;
    setTimeout( function() {
      window.location.href = "command:" + m;
    }, (__js2oc_wait - __diff_t));
  }
}
于 2011-09-29T11:59:52.893 回答
0

不,iframe 的 url 更改不会触发 shouldOverrideUrlLoading,至少在 Android 2.2 中不会。

于 2010-12-02T07:04:12.507 回答