我想说最好的方法是自己做,结合这两个例子:
function nativeDoStuff() {
if (androidbridge != null {
androidbridge.doStuff();
}
else {
//construct url
window.location = "myiphonescheme://dostuff";
}
想一想,如果你有雄心壮志,你可以编写一个快速的 javascript 对象来为你做这件事:
function NativeAppBridge () {
function runMethod(methodName, params) {
if (androidbridge != null {
// If the android bridge and the method you're trying to call exists,
// we'll just call the method directly:
if (androidbridge[methodName] != null) {
androidbridge[methodName].apply(this, params);
}
}
else {
// building the url is more complicated; best I can think
// of is something like this:
var url = "myiphonescheme://" + methodName;
if (params.length > 0) {
url += "?"
var i = 0;
for (param in params) {
url += "param" + i + "=" + param;
++i;
if (i < params.length) {
url += "&";
}
}
}
}
}
}
使用它就像这样简单:
var bridge = new NativeAppBridge();
function onClick() {
bridge.runMethod("doStuff", null);
}
请注意,我在脑海中编写了这个代码,目前没有时间进行测试 - 但我认为它应该足够好,前提是我没有犯任何重大错误