React Native How to pass data from javascript to java android - javascript

I followed the tutorial on this site:
https://facebook.github.io/react-native/docs/embedded-app-android.html
Now I want to have a function in my javascript code like this:
greetingFunction(){
return "HELLO, WORLD";
}
I want to pass the string "HELLO, WORLD" to my java android code and set the screen to display that string.
How can I do this?

You should create a custom module to call custom native methods in Java where you can pass the data you need.
For instance if your custom native module implements the following method:
#ReactMethod
public void myMethod(String message) {
// Here we show a toast message
Toast.makeText(getReactApplicationContext(), message, Toast.LENGTH_SHORT).show();
}
Then you can call that method from JavaScript:
NativeModules.MyCustomModule.myMethod("HELLO WORLD");
Be sure to properly follow all steps described in the doc above to properly register your custom module.

Related

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 :)

Can I run JavaScript inside Swift code?

I need to include JavaScript code in Swift code to be able to call a signalR chat, is that possible? If not, can I convert it?
sendmessage is a button.
$(function () {
// Declare a proxy to reference the hub.
var chat = $.connection.chatHub;
// Create a function that the hub can call to broadcast messages.
chat.client.broadcastMessage = function (name, message) {
// some code
};
// Start the connection.
$.connection.hub.start().done(function () {
$('#sendmessage').click(function () {
// Call the Send method on the hub.
chat.server.send('name', 'message');
});
});
});
and the signalr code is:
public void Send(string name, string message)
{
// Call the broadcastMessage method to update clients.
Clients.All.broadcastMessage(name, message);
}
Update #1:
changed question a little bit so it is not confusing per #MartinR
Last tested with Swift 5.1
Here is an example you can run in Playground to get you started:
import JavaScriptCore
let jsSource = "var testFunct = function(message) { return \"Test Message: \" + message;}"
var context = JSContext()
context?.evaluateScript(jsSource)
let testFunction = context?.objectForKeyedSubscript("testFunct")
let result = testFunction?.call(withArguments: ["the message"])
result would be Test Message: the message.
You also can run JavaScript code within a WKWebView calling evaluate​Java​Script(_:​completion​Handler:​).
You can also run JavaScript within a UIWebView by calling string​By​Evaluating​Java​Script(from:​), but note that that method has been deprecated and is marked as iOS 2.0–12.0.
Using JavaScriptCore framework include JavaScript code in Swift code.
The class that you’ll be dealing the most with, is JSContext. This class is the actual environment (context) that executes your JavaScript code.
All values in JSContext, are JSValue objects, as the JSValue class represents the datatype of any JavaScript value. That means that if you access a JavaScript variable and a JavaScript function from Swift, both are considered to be JSValue objects.
I strongly advise you to read the official documentation regarding the JavaScriptCore framework. 
import JavaScriptCore
var jsContext = JSContext()
// Specify the path to the jssource.js file.
if let jsSourcePath = Bundle.main.path(forResource: "jssource", ofType: "js") {
do {
// Load its contents to a String variable.
let jsSourceContents = try String(contentsOfFile: jsSourcePath)
// Add the Javascript code that currently exists in the jsSourceContents to the Javascript Runtime through the jsContext object.
self.jsContext.evaluateScript(jsSourceContents)
}
catch {
print(error.localizedDescription)
}
}
more details refer this tutorial

Pass object from Javascript to C++/CX based on C++/CX interface - Windows Runtime Components

I'm new to Windows Runtime Component, and have been trying to figure out how to achieve the following.
The C++ interface I want to extend from in Javascript.
namespace MySDK {
public interface class LoggerPlugin
{
public:
virtual void Log (Platform::String^ Tag, Platform::String^ Messsage);
};
}
The C++
namespace MySDK {
public ref class Logger sealed : public Platform::Object
{
public:
static Logger^ GetInstance ();
void SetPlugin (LoggerPlugin^ Plugin);
};
}
What I tried, may seem silly, but I have no idea how to achieve it.
var plugin = {
log: function(tag, message) {
console.log(tag + ':' + message);
}
};
MySdk.Logger.getInstance().setPlugin(plugin);
The error that I get is
JavaScript runtime error: Type mismatch
I couldn't find any documentation or examples on how to achieve this, will appreciate if anyone could provide me an example of how this can be done.
JavaScript cannot implement WinRT interfaces. If you want to have a JavaScript implementation of your plugin, then you will need to build a concrete type that raises events (that JavaScript can subscribe to) rather than defining virtual methods (that C++ or C# could implement).

How to create an C#.Net DLL to use in JavaScript

I have created a .Net DLL with few simple classes. I have registered the DLL using RegAsm and I got a message that types were registered successfully.
RegAsm Syntax Used :
C:\Windows\Microsoft.NET\Framework\v4.0.30319>RegAsm.exe "D:\Projects\TestDLL.Core.dll"
C# Code:
namespace MyTestDLL.Core
{
public class PacketInfo
{
// constructor
public PacketInfo()
{
}
public string HostName { get; set; }
// and so on ......
}
}
I have set the ComVisible property to true in AssemblyInfo.cs file of this DLL.
// [assembly: ComVisible(true)]
However when I create an object out of it in JavaScript and run the script in Command prompt , I'm getting either it is not an object or null.
JS Code :
var testObj = new ActiveXObject(MyTestDLL.Core.PacketInfo);
testObj.HostName = "Test";
Can anyone advise me how to resolve this ?
You need to add a ProgId attribute to the class, something like this:
[Guid("some guid that you will never change")]
[ProgId("MyLib.PacketInfo")] // this is arbitrary
public class PacketInfo
{
....
}
The guid is optional, but if you don't set it yourself, it will be something you won't control, so it's better to define it. And of course I did not add the ComVisible because you already defined it at assembly level (I personnally prefer to set it at class level).
Then, once registered, you shall be able to use it like this (use the progid as a string):
var testObj = new ActiveXObject('MyLib.PacketInfo');
testObj.HostName = "Test";
I was able to achieve that by adding the following line to My DLL just above the class,
[Guid("A32AB771-9967-4604-B193-57FAA25557D4"), ClassInterface(ClassInterfaceType.None)]
Earlier I wasn't having the ClassInterfaceType part in my code.
Also ensure that each of your classes are having unique GUID.
FYI : You can create GUID using Visual Studio Tools GUID Creator GUI.

Android, extract javascript variable from webview using javascript interface

How can I extract this variable bellow from a website to my android code?
I guess it should work using javascript interface but how do I get it?
<script type="text/javascript">
var Ids = "[4161, 104, 121, 202, 1462]";
</script>
And I can't change the code on the website to a method that returns the value.
Any suggestions?
You can use the javascript: scheme in a webview.loadurl call. It will execute the javascript in the webview page.
From there you can make it call a function in your javascript interface.
webview.loadUrl("javascript:Android.getIds(Ids);");
Android being the name space used to declare your javascript interface.
//Add the javascript interface to your web view
this.addJavascriptInterface(new CustomJavaScriptInterface(webViewContext), "Android");
Beware that javascriptinterface only work with primitive types. So you actually can't pass directly an array. Just use the javascript scheme to loop through your array. I see it is not really an array so you should be fine with just :
public class CustomJavaScriptInterface {
Context mContext;
/** Instantiate the interface and set the context */
CustomJavaScriptInterface(Context c) {
mContext = c;
}
/** retrieve the ids */
public void getIds(final String myIds) {
//Do somethings with the Ids
}
}

Categories

Resources