我在服务器上托管了一些 HTML5/javascript 文件。当在 HTML5 页面上单击按钮时,将调用 javascript 函数。我想监听函数何时被调用并获取函数返回的 json。以前我在设备上打开一个端口,但在 Android 3.0 上似乎不起作用。我听说您可以使用外部接口(interface) 来监听 javascript 调用,但我不知道如何实现。
最佳答案
要使用外部接口(interface),您需要在 WebView 中运行您的网站。此外,以下解决方案意味着什么
要注册您的界面,您需要调用 addJavascriptInterface WebView 实例上的方法。您需要为其选择一个名称并创建一个实现。您的界面应该拦截函数调用并报告其结果,所以,让我们描述一下...
class FunctionCallInterceptor {
public void reportCall(String functionName, String result) {
// some code, handling interception
}
}
然后注册...
mWebView.addJavascriptInterface(new FunctionCallInterceptor(), 'Interceptor');
有关 JavaScript 接口(interface)的更多信息,请参阅 Binding JavaScript
然后您需要将函数结果“传输”到您的界面...这里您需要一些 JavaScript 代码。
function wrapFunc(name) {
if(typeof window[name] == 'function') { // If target is accessible
var original = window['__' + name] = window[name]; // remember original one
window[name] = function() { // and replace with wrapper
var result = original.apply(this, arguments); // call original
Interceptor.reportCall(name, result.toString()); // report to interceptor
return result; // return result as usual
}
}
}
使用这段代码包装你的函数
wrapFunc('myFunction'); // wraps myFunction in the source
此外,不要忘记启用 JavaScript
mWebView.getSettings().setJavaScriptEnabled(true);
何时,如何将此代码嵌入到您的外部页面(我的意思是您无法访问外部 JS 代码)...要在页面上下文中执行任意代码,您可以使用 loadUrl WebView
mWebView.loadUrl('javascript:some... js... code...');
这不会触发页面重新加载,只会执行 JavaScript。请注意在页面完全加载后需要执行此操作的内容。您可以通过以下代码获取:
mWebView.setWebViewClient(new WebViewClient {
@Override
public void onPageFinished (WebView view, String url) {
// here page is loaded
}
});
参见 setWebViewClient和 onPageFinished详情
另请注意,通过 loadUrl 调用传输到页面的代码不得包含换行符。所以你需要摆脱它们(通过 String.replace 左右)。
添加 所以,最终的解决方案是:
String wrapFuncCode = "function wrapFunc ...... "; // or maybe place it in resources?
mWebView.addJavascriptInterface(new FunctionCallInterceptor(), 'Interceptor');
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.setWebViewClient(new WebViewClient {
@Override
public void onPageFinished (WebView view, String url) {
// inject wrapper
// don't forget to remove newline chars
mWebView.loadUrl("javascript:" + wrapFuncCode.replace('\n', ''));
// wrap all the functions needed
String[] funcToWrap = new String[] { 'myFunc1', ... };
for(String f : funcToWrap) {
mWebView.loadUrl("javascript:wrapFunc('" + f + "myFunction');");
}
}
});
关于android - 监听来自 java 的 javascript 函数调用 - Android,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9306801/
我想在一个没有Sass引擎的类中使用Sass颜色函数。我已经在项目中使用了sassgem,所以我认为搭载会像以下一样简单:classRectangleincludeSass::Script::FunctionsdefcolorSass::Script::Color.new([0x82,0x39,0x06])enddefrender#hamlengineexecutedwithcontextofself#sothatwithintemlateicouldcall#%stop{offset:'0%',stop:{color:lighten(color)}}endend更新:参见上面的#re
我真的很习惯使用Ruby编写以下代码:my_hash={}my_hash['test']=1Java中对应的数据结构是什么? 最佳答案 HashMapmap=newHashMap();map.put("test",1);我假设? 关于java-等价于Java中的RubyHash,我们在StackOverflow上找到一个类似的问题: https://stackoverflow.com/questions/22737685/
我正在尝试用ruby中的gsub函数替换字符串中的某些单词,但有时效果很好,在某些情况下会出现此错误?这种格式有什么问题吗NoMethodError(undefinedmethod`gsub!'fornil:NilClass):模型.rbclassTest"replacethisID1",WAY=>"replacethisID2andID3",DELTA=>"replacethisID4"}end另一个模型.rbclassCheck 最佳答案 啊,我找到了!gsub!是一个非常奇怪的方法。首先,它替换了字符串,所以它实际上修改了
我正在尝试编写一个将文件上传到AWS并公开该文件的Ruby脚本。我做了以下事情:s3=Aws::S3::Resource.new(credentials:Aws::Credentials.new(KEY,SECRET),region:'us-west-2')obj=s3.bucket('stg-db').object('key')obj.upload_file(filename)这似乎工作正常,除了该文件不是公开可用的,而且我无法获得它的公共(public)URL。但是当我登录到S3时,我可以正常查看我的文件。为了使其公开可用,我将最后一行更改为obj.upload_file(file
我有一些代码在几个不同的位置之一运行:作为具有调试输出的命令行工具,作为不接受任何输出的更大程序的一部分,以及在Rails环境中。有时我需要根据代码的位置对代码进行细微的更改,我意识到以下样式似乎可行:print"Testingnestedfunctionsdefined\n"CLI=trueifCLIdeftest_printprint"CommandLineVersion\n"endelsedeftest_printprint"ReleaseVersion\n"endendtest_print()这导致:TestingnestedfunctionsdefinedCommandLin
如何在ruby中调用C#dll? 最佳答案 我能想到几种可能性:为您的DLL编写(或找人编写)一个COM包装器,如果它还没有,则使用Ruby的WIN32OLE库来调用它;看看RubyCLR,其中一位作者是JohnLam,他继续在Microsoft从事IronRuby方面的工作。(估计不会再维护了,可能不支持.Net2.0以上的版本);正如其他地方已经提到的,看看使用IronRuby,如果这是您的技术选择。有一个主题是here.请注意,最后一篇文章实际上来自JohnLam(看起来像是2009年3月),他似乎很自在地断言RubyCL
我正在尝试使用boilerpipe来自JRuby。我看过guide从JRuby调用Java,并成功地将它与另一个Java包一起使用,但无法弄清楚为什么同样的东西不能用于boilerpipe。我正在尝试基本上从JRuby中执行与此Java等效的操作:URLurl=newURL("http://www.example.com/some-location/index.html");Stringtext=ArticleExtractor.INSTANCE.getText(url);在JRuby中试过这个:require'java'url=java.net.URL.new("http://www
我需要一些关于TDD概念的帮助。假设我有以下代码defexecute(command)casecommandwhen"c"create_new_characterwhen"i"display_inventoryendenddefcreate_new_character#dostufftocreatenewcharacterenddefdisplay_inventory#dostufftodisplayinventoryend现在我不确定要为什么编写单元测试。如果我为execute方法编写单元测试,那不是几乎涵盖了我对create_new_character和display_invent
我只想对我一直在思考的这个问题有其他意见,例如我有classuser_controller和classuserclassUserattr_accessor:name,:usernameendclassUserController//dosomethingaboutanythingaboutusersend问题是我的User类中是否应该有逻辑user=User.newuser.do_something(user1)oritshouldbeuser_controller=UserController.newuser_controller.do_something(user1,user2)我
什么是ruby的rack或python的Java的wsgi?还有一个路由库。 最佳答案 来自Python标准PEP333:Bycontrast,althoughJavahasjustasmanywebapplicationframeworksavailable,Java's"servlet"APImakesitpossibleforapplicationswrittenwithanyJavawebapplicationframeworktoruninanywebserverthatsupportstheservletAPI.ht