简体   繁体   English

检测是否存在javascriptinterface方法

[英]Detect if a javascriptinterface method exists or not

I have an Android Project that is already in play store and being installed on many devices. 我有一个Android项目已经在Play商店中,并已安装在许多设备上。 In my previous version there was not any method in java to check the version of app that was being called from javascript. 在我以前的版本中,java中没有任何方法可以检查从javascript调用的应用程序的版本。

Then I developed a new version of app and added a javascriptinterface function to return version of the app installed. 然后,我开发了新版本的应用程序,并添加了javascriptinterface函数以返回安装的应用程序的版本。 Now I want my client to update app if there is old version installed on their device. 现在,如果他们的设备上安装了旧版本,我希望我的客户端更新应用程序。

Because that javascriptinterface function was not exist in old app, when I call that method for old apps it does not do anything as the method do not exists in old app. 由于旧应用程序中不存在该javascriptinterface函数,因此当我为旧应用程序调用该方法时,它不会执行任何操作,因为该方法在旧应用程序中不存在。 Its working fine in new app. 在新应用程式中运作良好。

My question is: Is there any way to detect if a javascriptinterface function exists or not from old app version where that method wasn't even defined??? 我的问题是:有没有办法从甚至没有定义该方法的旧应用程序版本中检测到javascriptinterface函数是否存在?

If I am getting this right, than, in your new version, a new method was added for to the javascript engine, by java, such that window.getAppVersion() yields the current version (assuming the method name is indeed »getAppVersion«). 如果我做对了,那么,在您的新版本中,java将新方法添加到javascript引擎,以便window.getAppVersion()产生当前版本(假设方法名称的确是»getAppVersion«) 。

To check if that method exists in Javascript a certain scope ( window in this case), you can do: 要检查某个方法在Javascript中是否存在该方法(在这种情况下为window ),可以执行以下操作:

if ('getAppVersion' in window) { … }

so you can add something like that to the beginning of the script: 因此您可以在脚本的开头添加类似的内容:

if (!('getAppVersion' in window)) {
  window.getAppVersion = function () {
    //really old verion
    return -Infinity;
  }
}

That way you create the function only if it not exists. 这样,仅当函数不存在时才创建该函数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM