Created
June 29, 2020 13:48
-
-
Save ZhihaoLau/f654a79067dfb829382735ebbe2973ac to your computer and use it in GitHub Desktop.
ywapi.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(function () { | |
/** | |
* YWApiCore | |
*/ | |
YWApiCore = { | |
__GLOBAL_FUNC_INDEX__: 0, | |
invokeClientMethod: function (module, name, parameters, callback) { | |
var url = "mm://" + module + "/" + name + "?p=" + encodeURIComponent(JSON.stringify(parameters || {})); | |
if (callback) { | |
var name; | |
if (typeof callback == "function") { | |
name = YWApiCore.createGlobalFuncForCallback(callback); | |
} else { | |
name = callback; | |
} | |
url = url + "&cb=" + name; | |
} | |
console.log("[API]" + url); | |
window.webkit.messageHandlers.YYWKWebViewAPI.postMessage(url); | |
}, | |
createGlobalFuncForCallback: function (callback) { | |
if (callback) { | |
var name = "__GLOBAL_CALLBACK__" + YWApiCore.__GLOBAL_FUNC_INDEX__++; | |
window[name] = function () { | |
var args = arguments; | |
var func = typeof callback == "function" ? callback : window[callback]; | |
//we need to use setimeout here to avoid ui thread being frezzen | |
setTimeout(function () { | |
func.apply(null, args); | |
}, 0); | |
}; | |
return name; | |
} | |
return null; | |
}, | |
invokeWebMethod: function (callback, returnValue) { | |
YWApiCore.invokeCallbackWithArgs(callback, [returnValue]); | |
}, | |
invokeCallbackWithArgs: function (callback, args) { | |
if (callback) { | |
var func = null; | |
var tmp; | |
if (typeof callback == "function") { | |
func = callback; | |
} else if ((tmp = window[callback]) && typeof tmp == "function") { | |
func = tmp; | |
} | |
if (func) { | |
setTimeout(function () { | |
func.apply(null, args); | |
}, 0); | |
} | |
} | |
}, | |
}; | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment