How can you access javascript variables from a C#.Net Webbrowser object? - javascript

I want to create a Webbrowser .Net object from my C#.Net Winform application and then be able to access javascript variables.
Basically I want to take some action in my main Winform application depending on some user interactions that happen that set javascript variables.
Any advice on how I can make calls to the Webbrowser object to do this?
Note I did look at the Document property that lets you get at the DOM but don't understand how/if that can be used to get at javascript variables.
Dan

In the WinForms browser, use the ObjectForScripting property to handle two-way communications between your WinForms application and your WebBrowser's Document.
You can invoke javascript members from C# through the Document object:
// C# code
webBrowser1.Document.InvokeScript("test",
new String[] { "called from client code" });
Assigning ObjectForScripting as
// C# code
webBrowser1.ObjectForScripting = obj;
appears to allow the hosted javascript to call members of obj, e.g.
// javascript code
window.external.SomeMethod('called from script code');
// executes obj.SomeMethod(string) in C#
Disclaimer: I only have experience with the WPF web browser, so I haven't verified the above myself.

Make use of CeSharp, a Chromium Embedded Framework that allows much more control over your webbrowser component.
To get started
Fire up a VS project
Open nuget console and execute: Install-Package CefSharp.WinForms if you are doing Winforms C# App.
Restart your Visual studio and re-load project.
Example of CefSharp code to get started.
Add a toolStripContainer to your form from the toolbox then use the following example code to load cefsharp browser component.
public Form1()
{
InitializeComponent();
var browser = new ChromiumWebBrowser("http://localhost:1071/");
browser.Dock = DockStyle.Fill;
toolStripContainer1.ContentPanel.Controls.Add(browser);
}
This should get you started, in order to talk to JS from C# you will need to make use of EvaluateScript interface.
Take a look at the following resource.
https://github.com/cefsharp/CefSharp/issues/368

Related

How to access C# dll using JavaScript

i have a class library in c# and i added that dll as a reference to the web site and I want to access the methods which are in the class library.
when I tried accessing those methods using ActiveXobject it throwing an exception saying object cant be created
namespace Office
{
public class Algebra
{
public double Addition(double x, double y)
{
return x + y;
}
}
}
this is my method in c# class library.
and my javascript is as follows
(function () {
alert("suresh");
var myobj;
myobj = new ActiveXObject("Office.Algebra");
alert(myobj);
var add = myobj.Addition(7, 6);
alert(add);
})();
No! Don't go this way.
If you want to access server resources from the client-side, you'll need to design and implement a Web service, for example on top of REST principles, which drives you directly to ASP.NET Web API.
In summary: expose resources from the backend using a Web service and access them using AJAX.
If I'm not mistaken in guessing, you have a dll that you want to run on the web browser (iirc, only IE). If that's the case, then you have to register the dll on the client computer ( with regsvr, regasm, depending on your dll).
But I agree with Matias, use it as last resort, for example, you have to call this dll for some legacy hardware requirement, legacy app, etc, and you've spent 3 months at least looking for another way. :p

Execute javascript without webview in Android

I'm trying to execute a JS fonction in my Android app.
The function is in a .js file on a website.
I'm not using webview, I want to execute the JS function because it sends the request i want.
In the Console in my browser i just have to do question.vote(0);, how can I do it in my app ?
UPDATE 2018: AndroidJSCore has been superseded by LiquidCore, which is based on V8. Not only does it include the V8 engine, but all of Node.js is available as well.
You can execute JavaScript without a WebView. You can use AndroidJSCore. Here is a quick example how you might do it:
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet("http://your_website_here/file.js");
HttpResponse response = client.execute(request);
String js = EntityUtils.toString(response.getEntity());
JSContext context = new JSContext();
context.evaluateScript(js);
context.evaluateScript("question.vote(0);");
However, this most likely won't work outside of a WebView, because I presume you are not only relying on JavaScript, but AJAX, which is not part of pure JavaScript. It requires a browser implementation.
Is there a reason you don't use a hidden WebView and simply inject your code?
// Create a WebView and load a page that includes your JS file
webView.evaluateJavascript("question.vote(0);", null);
For the future reference, there is a library by square for this purpose.
https://github.com/square/duktape-android
This library is a wrapper for Duktape, embeddable JavaScript engine.
You can run javascript without toying with WebView.
Duktape is Ecmascript E5/E5.1 compliant, so basic stuff can be done with this.

Transferring a javascript variable to to Objective C (IOS)

I am working on creating an app and am a relatively new Objective C programmer. On a page, "test.php", I have a javascript variable. Here is a simplified version.
<script>
var idx = 45;
document.write(idx);
</script>
I would like to be able to view the value of the variable "idx" in my IOS app, which I have created using Xcode. What would be the optimal way to connect to the page, test.php, and transfer my Javascript variable to Objective C so I could use it as part of my IOS App?
Any help would be greatly appreciated. Thank you.
You will need to communicate between the webview and the native code using a combination of two pieces. First, you will need to "trigger" the webview into returning some value by calling stringByEvaluatingJavaScriptFromString: on the webview. When the webview tries to navigate because of the javascript call, you can intercept it on the native side with the WebView's shouldStartLoadWithRequest: method.
For details, see the specifics here Invoke method in objective c code from HTML code using UIWebView
That is only if you need some activity in the webview to trigger the fetch (or notify the native code that the value has been set). If the value is always available via JS, you can simply use stringByEvaluatingJavaScriptFromString: as follows:
NSString *returnvalue = [self.webviewForHtml stringByEvaluatingJavaScriptFromString:#"var idx = "return_value";return idx;"];

Write a variable to a file in Javascript

This may be a copy.. but I'm not getting the thing I want from the answers I saw..
I just want to save a particular variable into a local file using Javascript. I know how to read a file.
I wrote this code..
<script>
var fs = require('fs');
fs.writeFile('http://localhost/online/hello.txt', 'Hello Node', function (err) {
if (err) throw err;
else
{
console.log('It\'s saved!');
}
});
</script>
What is the error here.. or is there a simple and straight-forward way of doing it..??
It seems you're trying to call node-js code from the browser. Although javascript can run in both the browser and on the server (node-js), those are separate systems.
Another thing you can do is google "HTML save file example" and see how this is typically implemented - by opening a save dialog for the user, getting his/her permission, etc. (otherwise any website could just write any file to your computer...).
You are writing NodeJS code for client side application. You must understand the difference between javascript on browser and javascript on NodeJS platform.
Javascript is a language just like C, Java and Python
V8 is a javascript engine to run the javascript application. It is something similar to JRE for Java.
Browser(Only Chrome) uses V8 engine for running javascript application. Other browsers use different javascript engine. Five years ago, there was only one possibility that javascript can only work on browser. You cannot use javascript for application programming like C and Java
NodeJS is a platform which uses V8 to enables developer to write javascript application just like C, Java program. NodeJS also has some inbuilt library for accessing file system,
networks, and much more utilities. One of the internal library in NodeJS is fs. It only works on NodeJS application, not on browser application.
This can be done pretty simply using jrpc-oo. jrpc-oo links the browser and nodejs using the JRPC2 protocol. jrpc-oo abstracts classes over JRPC so that either side (nodejs or the browser) can call eachother.
I have setup an example repo to do exactly this here. Use the writeToFile baranch. I will break out the important parts here.
First in nodejs, we write a class with a method to write input arguments to file. The method looks like so (from the file TestClass.js) :
const fs = require('fs');
class TestClass {
writeToFile(arg){
fs.writeFileSync('/tmp/browser.json',JSON.stringify(arg));
}
}
In the browser we inherit from the jrpc-oo class JRPCClient and call the server class TestClass and method writeToFile like so (from the file src/LitJRPC.js) :
import {JRPCClient} from '#flatmax/jrpc-oo/jrpc-client.js';
export class LitJRPC extends JRPCClient {
writeObjToFile(){
// create the argument we want to save to file
let dat={name:'var',value:10};
// Ask the server to execute TestClass.writeToFile with args dat
this.server['TestClass.writeToFile'](dat);
}
}
Finally we run the nodejs app and the web-dev-server and we look at the browser console and nodejs console to see what happened. You will see the browser variable dat saved to the file /tmp/browser.json
As we are using a secure websocket for jrpc, you will need to generate the certificate and clear the certificate with the browser before the app will work. If you don't want to worry about security then don't use secure websockets. Read the readme in the reference repo for more information on setup and usage.

How to call user32.dll methods from javascript

I have a javascript running on a browser. Is it possible to call a function/method in user32.dll.
This is possible from C# by using pInvoke calls. How do I do the same in JavaScript?
Thanks,
Datte
Because of the JavaScript sandbox, you can't do it without a middle layer requiring elevated security permissions, such as a Netscape-style browser plug-in (widely supported), ActiveX control (pretty much IE-only), or .Net control (I assume that's possible; again probably IE-only). In each case, the JavaScript would talk to the control, which would in turn make the USER32 call for you.
None of that will work without the user having granted your application elevated permissions, but I'm guessing as you're requiring Windows, this is for some kind of intranet application where that may be possible.
You definitely need a plug-in, extension or ActiveX of your own installed on the client.
In the case of a firefox extension, you can use jsctypes to wrap the calls easily.
If you use the Jetpack API included with Firefox 4, it will be all JavaScript and won't even require a browser restart.
Here's an exemple from mozilla.org for a basic Hello World :
/* Load JS Ctypes Javascript module */
require("chrome").Cu.import("resource://gre/modules/ctypes.jsm");
/* Load windows api dll */
var lib = ctypes.open("user32.dll");
/* Declare the signature of the function we are going to call */
var msgBox = lib.declare("MessageBoxW",
ctypes.stdcall_abi,
ctypes.int32_t,
ctypes.int32_t,
ctypes.ustring,
ctypes.ustring,
ctypes.int32_t);
var MB_OK = 3;
/* Do it! */
var ret = msgBox(0, "Hello world", "title", MB_OK);
/* Display the returned value */
alert("MessageBox result : "+ret);
lib.close();
On the client - it is not possible for security reasons (imagine every site could run system commands on your computer... end of the world - maybe possible with an ActiveX, but that's IE only, but then again, the DLL is windows only).
If you want to run it on the server you'll need to go trough AJAX and C#.
Run dll methods on the client machine using javascript from a web page? That's what is gonna trigger apocalypse.
If you build your own web browser in C#, you can intercept JavaScript calls and translate them to whatever you want in your browser. Though that won't work if you want it to be available to other browsers.
Write a com object that wraps your call to user32. Invoke it in IE/javascript.
Your DynamicWrapperX object would work for this (it would BE that com object, allowing you to just call your dlls as you wish).

Categories

Resources