PhoneGap如何在更改window.location/document.location后保持Javascript的
How PhoneGap keep Javascript executing after changing window.location/document.location
根据这个问题,当我们设置window.location时,javascript将"停止"执行或变成竞争条件。
有时,我们需要在WebView中多次触发window.location = SOMESCH://xxx
,才能将"通知"发送回我们的应用程序。例如,设置window.location = myapp://loginButtonEnabled?e=1
来告诉应用程序用户已经填写了一些nessaary信息,可以开始登录。似乎不可能做这样的事情:
function(){
window.location = myapp://loginButtonEnable?e=1;
window.location = myapp://hideHintView;
.....
window.location = myapp://theLastThing;
}
只有最后一个window.location = myapp://theLastThing
将被触发,然后Javascript的执行将停止(尽管我们通过在webView:shouldStartLoadWithRequest:navigationType:
中返回NO来停止应用程序中的重定向)。
我发现PhoneGap通过使用调度队列实现这一点很有趣,但我仍然不明白它为什么有效,有人知道诀窍吗??
顺便说一句,有没有一种简单的方法可以在设置位置后"恢复"执行?这将比使用操作队列要好得多。
每次都需要给事件循环一个响应位置更改的机会。执行此操作的典型方法是使用具有小/零延迟的setTimeout
,其效果是将执行移动到下一个事件循环节拍。试试这样的东西:
var q=[];
function dequeue() {
window.location='myapp://'+q.shift();
if (q.length>0) setTimeout(dequeue,0);
}
function notifyApp(cmd) {
q.push(cmd);
if (q.length==1) setTimeout(dequeue,0);
}
notifyApp('loginButtonEnable?e=1');
notifyApp('hideHintView');
notifyApp('theLastThing');
至于javascript执行停止,设置window.location
不应该有这种效果,除非它真的导致页面更改——也许可以尝试使用上面的技术,看看你的javascript在最后一次notifyApp()
调用后是否继续。
编辑:解决这个问题的另一种方法是创建临时iframe,而不是更改当前页面的位置-例如触发应使用多个窗口启动LoadWithRequest。location.href调用
- 对象.在document.location上进行观测
- PhoneGap如何在更改window.location/document.location后保持Javascript的
- Javascript document.location.reload不起作用
- 了解document.location.htm何时完成
- 通过document.location以javascript中的字符串形式传递文件路径
- 使用document.location=file_url.mp3触发从JS下载-不正确
- document.location 在后续代码之后颁布
- Routing.navigate vs document.location.hash
- Javascript button and document.location
- Javascript 页面呈现为文本,而不是执行 document.location
- 保证在任何 document.location 更改之前执行 Javascript AJAX
- 如何使用 PHP 获取 document.location.href 的值
- JQuery - 在 window.location 之后使用 $(document).ready()
- JavaScript document.location.href 似乎期待 HTML
- 在 JavaScript 中为 document.location 创建钩子
- Javascript - 我可以拦截对 document.location.href 的调用吗?
- childwindow.document.location.reload() 不起作用
- document.location 在尝试下载文件时修改 WebApi 路由
- 当location.href和document的值时,是否存在任何情况.URL将有所不同
- 动态渲染单击document.location