How to cast an Object from Javascript to a class? - javascript

I have the following ActionScript code :
import flash.external.*
public function req(temp:Object):void{
var request:URLRequest=temp as URLRequest; // request is then null
}
ExternalInterface.addCallback('call',req);
and the follwing JavaScript code
document.getElementById('flash').call(({url:"http://ytrezq.sdfeu.org/flashredirect/?https://chromium-review.googlesource.com/accounts/self/profile",digest:null,method:"DELETE",requestHeaders:null,data:null,contentType:null}));
Or is it possible to cast the Javascript object to Urlrequest from JavaScript ? If not, how to do it from ActionScript ?
Please note I’m not interested in keeping the Original JavaScript Object…

Related

How can I access properties of Java Objects passed to scriptEngine?

I am passing an object to a scriptEngine using the engine.put() method, and am attempting to retrieve a property of said object using the engine.eval() method. However I can't seem to access them as the object seems to lose its methods when put in the engine, and the get() method I'd normally use in Javascript also seems to fail.
try {
ScriptEngine engine = new ScriptEngineManager().getEngineByName("graal.js");
engine.put("transformContext",transformContext);
engine.put("dataRecordsByName",transformContext.getDataRecordsByName());
//These three all return what I'm expecting - 2x the whole object and then just dataRecordsByName property
System.out.println(engine.get(transformContext));
System.out.println(engine.eval("print(transformContext"));
System.out.println(engine.get(dataRecordsByName));
//These throw errors get() and getDataRecordsByName() seemingly do not exist for transformContext in the engine
System.out.println(engine.eval("print(transformContext.getDataRecordsByName())"));
System.out.println(engine.eval("print(transformContext.get('dataRecordsByName'))"));
}catch(Exception e){
System.err.println("Error evaluating script: "+e.getMessage());
}
I have read that scriptEngine only imports public methods from public classes. In this case though TransformContext is public as are all its methods, so that should be fine?
Any help understanding this or a solution would be appreciated.
After some further research it seems that graal.js does not map properties as you may expect by default, but can do so if you run it in nashorn compatability mode.
System.setProperty("polyglot.js.nashorn-compat", "true");
After doing this, you can retrieve the object properties as you normally would in JavaScript:
engine.eval("console.log(transformContext.dataRecordsByName)");
Thanks to the guys on this thread:
https://github.com/oracle/graaljs/issues/169

Frida Casting object to List of Strings

I have been trying to print out the contents of a list when hooking an android app with Frida but am not having any luck.
The object I want to hook in Java looks like this
import com.fasterxml.jackson.annotation.JsonIgnore;
import java.util.List;
public final class Hello extends HelloParent{
#JsonIgnore
public final List sampleList;
}
There aren't any getters for this public object so I have to resort to using another object (Let's call the object "Bye")'s method (byeMethodB) to monitor this value.
This is what my frida-script looks like:
setTimeout(function() {
Java.perform(function(){
Java.use("Bye").byeMethodA.implementation = function(){
try{
//Returns a Hello object
var helloObject = Java.cast(this.byeMethodB(),Java.use("Hello"))
printListContent(Java.cast(helloObject.sampleList,Java.use("java.util.List"))))
}catch(err){
console.log(err)
}
}
})
},1000)
function printListContent(list){
var listIter = list.iterator()
while(listIter.hasNext()){
console.log(listIter.next())
}
}
Without casting the "helloObject.sampleList" object to a list, the output looks like this:
[object Object]
So I am sure it is not null
If I cast using Java.cast(helloObject.sampleList,Java.use("java.util.List")),
I get the following error:
I have also tried:
Java.cast(helloObject.sampleList,Java.use("java.util.List<>"))
(I am pretty sure its a String)
Java.cast(helloObject.sampleList,Java.use("java.util.List<String>"))
Java.cast(helloObject.sampleList,Java.use("java.util.List<java.lang.String>"))
Java.cast(helloObject.sampleList,Java.use("[String"))
Java.cast(helloObject.sampleList,Java.use("[Ljava.lang.String"))
It is not going well at all. Would appreciate some help
In Frida accessing fields is not identical as in Java. If you execute helloObject.sampleList in Frida you are getting the JavaScript object that describes the field, not the field value itself.
If you want the field value you have to execute helloObject.sampleList.value.
Therefore the following code should work:
Java.cast(helloObject.sampleList.value, Java.use("java.util.List"));
Generics only exists at compile time but frida is working at run-time. Therefore java.util.List<> and the other class names with angle bracket will never work.

Send Object from Javascript to Kotlin using Webview

I have loaded a webpage using WebView component and added a JavascriptInterface. Please check the code below,
val webview = WebView(this)
setContentView(webview)
webview.settings.javaScriptEnabled = true
webview.loadUrl(HOME_PAGE_URL)
webview.addJavascriptInterface(JavascriptInterface(),”javascript_bridge”)
And when I call the invoke from Javascript using window.javascript_bridge.showToast(“Information Saved”);
private inner class JavascriptInterface
{
#android.webkit.JavascriptInterface
fun showToast(text: String?)
{
Log.d("WEBVIEW", text);
}
}
I am able to call the method from Javascript to Kotlin without any trouble.
But now I want to pass an Object from Javascript to Kotlin like below,
var info = {
message: “Information Saved”,
ID: 123456
}
And when I call the invoke from Javascript using window.javascript_bridge.showToast(info);
I tried to change to the data type to Any, but the value passed from Javascript is null
private inner class JavascriptInterface
{
#android.webkit.JavascriptInterface
fun showToast(text: Any?)
{
Log.d("WEBVIEW", text.toString());
}
}
As far as i know, the javaScript interface methods only accepts primitive types of data as parameters (as discussed on this question).
If you still want to achieve that, you may serialize the object (to JSON format, for instance) in the javaScript and then Deserialize it in Java.
Hope it helps :)

Supply JavaScript date to Nashorn script

I am working on an API in Java that allows users to write scripts and access a specific set of methods that are passed in (in the form of an API object) by the Nashorn script engine.
I want to, in the JavaScript, call a function getDate(), which will return some arbitrary date (as a native JavaScript date) that's provided from the Java side.
I have tried simply putting an org.java.util.Date on the API object, but that won't behave like a JS date. The goal is to make this as simple as possible for end-users who are experienced with JS.
Java Example:
public class MyAPI {
public void log(String text){
System.out.println(text);
}
public Date getDate(){
// Return something that converts to a native-JS date
}
public static void main(){
// MyClassFilter implements Nashorn's ClassFilter
ScriptEngine engine = new NashornScriptEngineFactory().getScriptEngine(new MyClassFilter());
((Invokable) engine).invokeFunction("entryPoint", new MyAPI());
}
JavaScript example
function entryPoint(myApi){
var date = myApi.getDate();
myApi.log(date.getMinutes());
}
jdk.nashorn.internal.* packages are nashorn internal implementation classes. There is no guarantee that these won't be changed or be removed between JDK versions. Besides with a security manager around, accessing these packages from java code directly would result in SecurityException being thrown! With jdk9 modular jdk, these packages are not exported packages from nashorn module and so javac won't even compile your code in jdk9!
I'd recommend using JS wrapper (solution 1) in the answer by user "ug_". If you do have to call from Java, you can use API exported from jdk.nashorn.api.scripting package.
If "engine" is your javax.script.ScriptEngine of nashorn, then you can do something like the following:
import jdk.nashorn.api.scripting.*;
..
public Object getDate() {
// get JS Date constructor object - you can get once and store
// as well/
JSObject dateConstructor = (JSObject) engine.eval("Date");
// now do "new" on it
return dateConstructor.newObject();
}
With that, your JS script can call "getDate()" on your API object and get a JS
Date object. Note that you can also pass constructor arguments to newObject
method call (it is a Java variadic method).
The Nashorn engine has objects it uses internally which represent the Javascript objects. As you have guessed the java.util.Date != new Date() (in javascript). The engine uses a class called jdk.nashorn.internal.objects.NativeDate to represent its JS date.
If I were building this out I would not have the NativeDate constructed in the Java but instead have a wrapper in Javascript for the MyApi object which would contain a few other native JS methods, such as getDate().
var MYAPI_JAVASCRIPT = {
log: function() {
print(arguments);
},
getDate: function() {
return new Date();
}
}
You could then pass that object as the method parameter.
However if your really set on using the NativeDate in your Java code then you can construct one like so:
public NativeDate getDate() {
return (NativeDate) NativeDate.construct(true, null);
}

Calling javascript function in c++ with emscripten embind

This question comes in two parts. What I want to do is to put most of my program logic in c++ classes and some view related function in js (like DOM manipulation and styling.) I use emscripten embind the classes and it works fine while I don't know how to interact with the js code (there are really limited resources on their tutorial.)
I was thinking to pass a val object to the c++ class according to their tutorial (https://github.com/kripken/emscripten/wiki/Tutorial) The passing works just fine while the "call" function doesn't work. I got a compile time error.
Here is the example I tried which they put on their tutorial:
#include <emscripten/val.h>
using namespace emscripten;
int main(){
val Math = val::global("Math");
Math.call("abs",-10);
return 0;
}
and I got the following errors:
error: no matching member function for call to 'call'
Math.call("abs",-10);
~~~~^~~~
emscripten/1.5.6/system/include/emscripten/val.h:247:21: note: candidate template ignored: couldn't infer template argument 'ReturnValue'
ReturnValue call(const char* name, Args&&... args) const {
Basically it says the the compiler doesn't know the return type of the "call" function.
Did I do anything wrong or is there a better way to interact with js code?
Thanks,
yi
That's a common C++ problem. As a general rule, the following message should always make you double check in C++:
note: candidate template ignored: couldn't infer template argument 'ReturnValue' ReturnValue call(const char* name, Args&&... args) const
This mostly means that you tried to call a templated function but did not specify the necessary types.
If you look at the signature (in system/include/emscripten/val.h):
template<typename ReturnValue, typename... Args>
ReturnValue call(const char* name, Args&&... args) const
While it can infer Args quite fine, it has no idea, what ReturnValue might be. So calling this function should be done via e.g.:
Math.call<int>("abs",-10);

Categories

Resources