I need a way to use a Java API (jar) from the javascript code on the local client. Can this be achieved and how?
Context
I have a Java API (jar file) that allows to connect to a real time information feed. You can submit a query and, for example, print the events you will receive:
service.subscribe(query, evt -> print(evt));
That API can only be used on the client machine for legal reasons so I can't expose it as a web service from a server.
Goal
I would like to create a web page that gets data from a web service and combines it with the real time information data obtained from the Java API locally.
I am using angular 2 but happy to consider any suggestions.
Web service
I have seen various similar questions but the answers tend to be: expose the API via a web service - that is not possible in my case.
You can use java applets for this purpose.
You should start by making an applet that encloses the call to your method:
public class TestApplet extends Applet{
private ? service = ...;
public Object subscribe(Object query) {
return service.subscribe(query, evt -> print(evt));;
}
}
This applet can then be included in the html of the webpage:
<script src="https://www.java.com/js/deployJava.js"></script>
<script>
<!-- applet id can be used to get a reference to the applet object -->
var attributes = { id:'testApplet', code:'yourpackage.TestApplet', width:1, height:1} ;
var parameters = {jnlp_href: 'test_applet.jnlp'} ;
deployJava.runApplet(attributes, parameters, '1.6');
</script>
Then you can use javascript to call the methods:
var greeting = testApplet.subscribe("Test");
Note that applets are being phased out because of their security problems, but this is ok in an controlled and embedded environment.
The following oracle tutorial gives more information about this technique: Invoking Applet Methods From JavaScript Code
The only way I can think of is using the javafx webview: http://docs.oracle.com/javafx/2/webview/jfxpub-webview.htm
Basically:
you create your own java-based-"webbrowser" withjavafx
you can then expose the java api into the webview
you can open a normal html page (i.e. http://server.tld/mypage.html) within the webview and use javascript to access the api
in the javascript you can check if the site has been opened with a normal browser or with you custom webview by checking if the exposed api is available:
the java code for something like that:
WebView webView = new WebView();
jfxPanel.setScene(new Scene(webView));
webEngine = webView.getEngine();
webEngine.setJavaScriptEnabled(true);
webEngine.setConfirmHandler(new ModalConfirmDialog(self));
// get the window and pass the required daos
JSObject jsobj = (JSObject) webEngine.executeScript("window");
// pass the dataaccess to the js context
jsobj.setMember("javaapi", getApiInstance());
webEngine.load("http://whatever.tld/mypage.html");
in javascript:
if(!window.javaapi) {
alert("Unable to get local java api");
return;
}
Other possibilities:
Applets: they wont work because they need to be downloaded from the same source as the webpage (which you cant use because of licensing restrictions)
JSP/Servlet: cant be used because this means the api must reside on the server (again licensing restriction)
Java Javascript Engine: You can call javascript directly from java, but since you want the javascript in a webpage, this wont work either...
Simply you cannot run .jar file from java script (But you can execute from nodejs) You can use applet to do that. You can refer this link.
It might sound really weird but actually, there's such tool that enable's you to 'convert' from java to js. But of course it has it's limitations and in order to successfully apply it in your particular case w/o doing modifications and dancing with a tambourine, you should be extremely lucky. this tool is able to convert it to js and allows you to create a JS API for the converted JS, so that it can be accessible from other js scripts. What I'm talking about is GWT. You must have source files of a jar (it might be decompiled sources) including all sources of dependencies that are used by lib.
Maybe you can invest in building a bridge between your JS code and the jar using Nashorn.
It allows you to evaluate JS code and invoke JS functions from Java, so it may serve your usecase. You can build a Java layer to connect to the API from the jar and then publish the results to JS by calling some function using Nashorn.
Or you can make use of the ability to directly call Java functions from JS.
Here is a simple tutorial
I want Write a web page for service to Android device.
before every thing i want to check is there any javasscriptinterface object used in the WebView or not... if there is any detect that.
i am writing my new Exclusive security method for develop safe page.
All help appreciated.
The JavaScript Interface is added by the WebView as an Object of the window component.
So you can test JavaScript presence by doing :
if (window.MyJavascriptInterface)
{
// Interface present
}
else
{
// No Interface
}
Here is the Android documentation
I am developing an application for android in which I storing some data to shared preferences.
Now My question is can i fetch that data inside a web browser on same device??
For example:
when i run my application
I have stored something like this :
Key :User_Email
Value:abc#abc.com
and then close the application.
Now i am on android web browser and open my webpage on which i have added a button,On Clicking this Button I am trying to get that value from shared preferences.
Please help me...
Internet and android application are different things.
You can't do this directly, due to security reasons.
You can use the below example code:
String html = sharedPref.getString("KEY");
String mime = "text/html";
String encoding = "UTF-8";
webview.loadDataWithBaseURL(null, html, mime, encoding, null);
I have a native (windows) application that has an embedded web browser. Currently I'm invoking a javascript function from the backend (c++/c#). However, if javascript is disabled this fails and I'd like to provide a fallback mechanism. Is there a way to determine if javascript is disabled?
In the IE Web Control, you can simply force JavaScript on. Please refer to the following interfaces, which your host has to implement:
IDocHostUIHandler
IDocHostShowUI
IInternetSecurityManager
IServiceProvider
Another approach would be for your HTML page to query the window.external object and call a method on it, which you implement in your host, which sets a flag to true. Not being called would mean the JavaScript was not executed.
Wow, using web browser under mfc is really pain in the ass, you can do it by getting the IInternetSecurityManager, and check if is enabled to execute javascript by current policy, if user select to disable javascript on his IE, you will need to overwrite the value in the registry.
HRESULT hr = CoCreateInstance(CLSID_InternetSecurityManager, NULL,
CLSCTX_INPROC_SERVER,IID_IInternetSecurityManager, (void**)&pSecurityMgr);
int policy = URLPOLICY_ALLOW;
hr = pSecurityMgr->ProcessUrlAction(L"http://www.google.com", URLACTION_SCRIPT_RUN,
(BYTE*)&policy, sizeof(policy), NULL, 0, PUAF_TRUSTED, 0);
if hr = S_FALSE, javascript execution is disabled...
Is it possible to to take a screenshot of a webpage with JavaScript and then submit that back to the server?
I'm not so concerned with browser security issues. etc. as the implementation would be for HTA. But is it possible?
Google is doing this in Google+ and a talented developer reverse engineered it and produced http://html2canvas.hertzen.com/ . To work in IE you'll need a canvas support library such as http://excanvas.sourceforge.net/
I have done this for an HTA by using an ActiveX control. It was pretty easy to build the control in VB6 to take the screenshot. I had to use the keybd_event API call because SendKeys can't do PrintScreen. Here's the code for that:
Declare Sub keybd_event Lib "user32" _
(ByVal bVk As Byte, ByVal bScan As Byte, ByVal dwFlags As Long, ByVal dwExtraInfo As Long)
Public Const CaptWindow = 2
Public Sub ScreenGrab()
keybd_event &H12, 0, 0, 0
keybd_event &H2C, CaptWindow, 0, 0
keybd_event &H2C, CaptWindow, &H2, 0
keybd_event &H12, 0, &H2, 0
End Sub
That only gets you as far as getting the window to the clipboard.
Another option, if the window you want a screenshot of is an HTA would be to just use an XMLHTTPRequest to send the DOM nodes to the server, then create the screenshots server-side.
Another possible solution that I've discovered is http://www.phantomjs.org/ which allows one to very easily take screenshots of pages and a whole lot more. Whilst my original requirements for this question aren't valid any more (different job), I will likely integrate PhantomJS into future projects.
Pounder's if this is possible to do by setting the whole body elements into a canvase then using canvas2image ?
http://www.nihilogic.dk/labs/canvas2image/
A possible way to do this, if running on windows and have .NET installed you can do:
public Bitmap GenerateScreenshot(string url)
{
// This method gets a screenshot of the webpage
// rendered at its full size (height and width)
return GenerateScreenshot(url, -1, -1);
}
public Bitmap GenerateScreenshot(string url, int width, int height)
{
// Load the webpage into a WebBrowser control
WebBrowser wb = new WebBrowser();
wb.ScrollBarsEnabled = false;
wb.ScriptErrorsSuppressed = true;
wb.Navigate(url);
while (wb.ReadyState != WebBrowserReadyState.Complete) { Application.DoEvents(); }
// Set the size of the WebBrowser control
wb.Width = width;
wb.Height = height;
if (width == -1)
{
// Take Screenshot of the web pages full width
wb.Width = wb.Document.Body.ScrollRectangle.Width;
}
if (height == -1)
{
// Take Screenshot of the web pages full height
wb.Height = wb.Document.Body.ScrollRectangle.Height;
}
// Get a Bitmap representation of the webpage as it's rendered in the WebBrowser control
Bitmap bitmap = new Bitmap(wb.Width, wb.Height);
wb.DrawToBitmap(bitmap, new Rectangle(0, 0, wb.Width, wb.Height));
wb.Dispose();
return bitmap;
}
And then via PHP you can do:
exec("CreateScreenShot.exe -url http://.... -save C:/shots domain_page.png");
Then you have the screenshot in the server side.
This might not be the ideal solution for you, but it might still be worth mentioning.
Snapsie is an open source, ActiveX object that enables Internet Explorer screenshots to be captured and saved. Once the DLL file is registered on the client, you should be able to capture the screenshot and upload the file to the server withing JavaScript. Drawbacks: it needs to register the DLL file at the client and works only with Internet Explorer.
We had a similar requirement for reporting bugs. Since it was for an intranet scenario, we were able to use browser addons (like Fireshot for Firefox and IE Screenshot for Internet Explorer).
This question is old but maybe there's still someone interested in a state-of-the-art answer:
You can use getDisplayMedia:
https://github.com/ondras/browsershot
The SnapEngage uses a Java applet (1.5+) to make a browser screenshot. AFAIK, java.awt.Robot should do the job - the user has just to permit the applet to do it (once).
And I have just found a post about it:
Stack Overflow question JavaScript code to take a screenshot of a website without using ActiveX
Blog post How SnapABug works – and what they should do
I found that dom-to-image did a good job (much better than html2canvas). See the following question & answer: https://stackoverflow.com/a/32776834/207981
This question asks about submitting this back to the server, which should be possible, but if you're looking to download the image(s) you'll want to combine it with FileSaver.js, and if you want to download a zip with multiple image files all generated client-side take a look at jszip.
You can achieve that using HTA and VBScript. Just call an external tool to do the screenshotting. I forgot what the name is, but on Windows Vista there is a tool to do screenshots. You don't even need an extra install for it.
As for as automatic - it totally depends on the tool you use. If it has an API, I am sure you can trigger the screenshot and saving process through a couple of Visual Basic calls without the user knowing that you did what you did.
Since you mentioned HTA, I am assuming you are on Windows and (probably) know your environment (e.g. OS and version) very well.
If you are willing to do it on the server side, there are options like PhantomJS, which is now deprecated. The best way to go would be Headless Chrome with something like Puppeteer on Node.JS. Capturing a web page using Puppeteer would be as simple as follows:
const puppeteer = require('puppeteer');
(async () => {
const browser = await puppeteer.launch();
const page = await browser.newPage();
await page.goto('https://example.com');
await page.screenshot({path: 'example.png'});
await browser.close();
})();
However it requires headless chrome to be able to run on your servers, which has some dependencies and might not be suitable on restricted environments. (Also, if you are not using Node.JS, you might need to handle installation / launching of browsers yourself.)
If you are willing to use a SaaS service, there are many options such as
Restpack
UrlBox
Screenshot Layer
A great solution for screenshot taking in Javascript is the one by https://grabz.it.
They have a flexible and simple-to-use screenshot API which can be used by any type of JS application.
If you want to try it, at first you should get the authorization app key + secret and the free SDK
Then, in your app, the implementation steps would be:
// include the grabzit.min.js library in the web page you want the capture to appear
<script src="grabzit.min.js"></script>
//use the key and the secret to login, capture the url
<script>
GrabzIt("KEY", "SECRET").ConvertURL("http://www.google.com").Create();
</script>
Screenshot could be customized with different parameters. For example:
GrabzIt("KEY", "SECRET").ConvertURL("http://www.google.com",
{"width": 400, "height": 400, "format": "png", "delay", 10000}).Create();
</script>
That's all.
Then simply wait a short while and the image will automatically appear at the bottom of the page, without you needing to reload the page.
There are other functionalities to the screenshot mechanism which you can explore here.
It's also possible to save the screenshot locally. For that you will need to utilize GrabzIt server side API. For more info check the detailed guide here.
As of today Apr 2020 GitHub library html2Canvas
https://github.com/niklasvh/html2canvas
GitHub 20K stars | Azure pipeles : Succeeded | Downloads 1.3M/mo |
quote : " JavaScript HTML renderer The script allows you to take "screenshots" of webpages or parts of it, directly on the users browser. The screenshot is based on the DOM and as such may not be 100% accurate to the real representation as it does not make an actual screenshot, but builds the screenshot based on the information available on the page.
I made a simple function that uses rasterizeHTML to build a svg and/or an image with page contents.
Check it out :
https://github.com/orisha/tdg-screen-shooter-pure-js