Open a browser with java - javascript

I hava a java program with two buttons, one for chrome and one for firefox. I press one of them, and the browser starts at some particualar location on the screen and with smalles size.
i have try running terminal commands, something like this
"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" --profile-directory="Default" --app="data:text/html,<html><body><script>window.moveTo(198,60);window.resizeTo(1167,708);window.location='https://stackoverflow.com';</script></body></html>"
And it works, but only for chrome. I want at least chrome and firefox on both windows and linux.
Searching a little I have come across other solution. Running javascript on java, somethig like:
ScriptEngineManager factory = new ScriptEngineManager();
ScriptEngine engine = factory.getEngineByName("JavaScript");
engine.eval("window.open('https://stackoverflow.com')");
engine.eval("window.resizeTo(800,600)");
But Im getting compilation errors:
ReferenceError: "window" is not defined in <eval> at line number 1
And I don´t know whats going. Ideas?

For Windows, you can do something like this using Runtime:
Runtime rt = Runtime.getRuntime();
rt.exec("C:\\Program Files (x86)\\Mozilla Firefox\\firefox.exe stackoverflow.com");
I believe that you can do something similar for Google Chrome. I took a look to a code I implemented in the past for Chrome and it was a little different, but previous approach should work as well:
Runtime rt = Runtime.getRuntime();
rt.exec(new String[]{"cmd", "/c","start chrome http://www.stackoverflow.com"});
If you would like to do it for a Linux based OS, then you can use Runtime as well:
Runtime rt = Runtime.getRuntime();
rt("/usr/bin/firefox -new-window http://www.stackoverflow.com");
I remember I got some references from this page:
https://www.mkyong.com/java/open-browser-in-java-windows-or-linux/
Hope it can help you.

ScriptEngineManager runs the script on server side. window is a client-side object, you can't access it from server.
in another word since you are not executing your script in a browser, the window object is not defined.
You can try this way to open a website on your default browser of the operating system:
Desktop desktop=Desktop.getDesktop();
URI url = new URI("http://somewhere");
desktop.browse(url);
to open a non-default browser in Java you should use Runtime.exec()
for Windows OS try this it worked for me:
String browserPath = "C:/Program Files/Mozilla Firefox/firefox.exe";
String url = "http://somewhere";
try {
String[] b = {browserPath, url};
Runtime.getRuntime().exec(b);
}
catch (Exception exc) {
exc.printStackTrace();
}
for further information on how to use Runtime.exec() on others OS read here

Related

Edge Browser - iframe.document.open not working

We have some functionality for exporting data to an excel file.
When the 'export' button is clicked, some client-side javascript is called, firstly checking the client browser version, and based on this, deciding which way to render the excel document.
It is working in Chrome & Firefox & IE11 when tested locally.
However, when I remotely test using a windows 10 machine running Edge browser, the excel is not rendered.
I might add that my local machine is a Win7 machine and Im running VS2012 and IE11. The remote machine is Win10 with Edge, hence the need to test remotely.
I've tried the emulation in IE11 F12 dev tools but cant replicate the Edge error there.
An error of 'undefined or null reference' is thrown for 'open' when using the following code:
excelIFrame.document.open("txt/html", "replace");
excelIFrame.document.write(sHTML);
excelIFrame.document.close();
excelIFrame.focus();
excelIFrame.document.execCommand("SaveAs", true, "Spreadsheet.xls");
The iframe exists in the html and is not added dynamically.
<iframe id="excelIFrame" style="display:none"></iframe>
I have tried the following possible solutions to get this working, to no avail -
Possible Solution 1: Same 'undefined or null reference error when assigning the document to a temp var
var doc = excelIFrame.document;
doc.open("txt/html", "replace");
doc.write(sHTML);
doc.close();
doc.focus();
doc.execCommand("SaveAs", true, "Spreadsheet.xls");
Possible Solution 2: Using the contentWindow property of the iFrame. No error thrown, it just opens 'about:blank' containing no content.
excelIFrame.contentWindow.contents = sHTML;
excelIFrame.src = 'javascript:window["contents"]';
Totally at a loss with this at this stage.
The page is an angularJS web page.
From reading up on it, I'm aware the document.open is problematic in edge when using iframes. But the following link document.open fails in an iframe I felt would solve the problem.
Any thoughts or suggestions greatly appreciated.
This may be helpful to others who are searching for it.
//For Edge browser ….. U have to write separate logic for each browser
if (ua.match(/Edge/)){
var blob = new Blob([sHTML], {type: 'data:application/vnd.ms-excel'});
window.navigator.msSaveBlob(blob, "P2P_Report_"+new Date().getTime()+".xls");
}

Open a link in an Incognito Window in Google Chrome

Is there any way to do this through Java or Javascript, given the link as a String? I've been looking but I've only found topics about Android devices, I'm asking for a Windows PC.
I hadn't planned on learning how to write an extension with the proper permissions for Chrome for this, but if that's the only way then so be it.
To run any executable including Chrome in JAVA:
If the path to the application is a system variable:
String location = System.getenv("APPVARIAVLE");
Process process = new ProcessBuilder(location).start();
Or if you want to use the fully qualified path:
Process process = new ProcessBuilder("C:\\location\\MyApp.exe").start();
The JavaDoc for the process builder say that you can add parameters like this:
new ProcessBuilder("myCommand", "myArg1", "myArg2");
The argument for incognito looks like it is: "-incognito" and to open a url just add the url: "example.com".
Which means that you can most likely can add the url and incognito arguments the following way to chrome in the arguments:
Process process = new ProcessBuilder("C:\\YourChrome\\Location\\chrome.exe","-incognito","http://stackoverflow.com").start();

How to make a 'protocol' of my own and a Desktop application to use it for a Browser? [duplicate]

How do i set up a custom protocol handler in chrome? Something like:
myprotocol://testfile
I would need this to send a request to http://example.com?query=testfile, then send the httpresponse to my extension.
The following method registers an application to a URI Scheme. So, you can use mycustproto: in your HTML code to trigger a local application. It works on a Google Chrome Version 51.0.2704.79 m (64-bit).
I mainly used this method for printing document silently without the print dialog popping up. The result is pretty good and is a seamless solution to integrate the external application with the browser.
HTML code (simple):
Click Me
HTML code (alternative):
<input id="DealerName" />
<button id="PrintBtn"></button>
$('#PrintBtn').on('click', function(event){
event.preventDefault();
window.location.href = 'mycustproto:dealer ' + $('#DealerName').val();
});
URI Scheme will look like this:
You can create the URI Scheme manually in registry, or run the "mycustproto.reg" file (see below).
HKEY_CURRENT_USER\Software\Classes
mycustproto
(Default) = "URL:MyCustProto Protocol"
URL Protocol = ""
DefaultIcon
(Default) = "myprogram.exe,1"
shell
open
command
(Default) = "C:\Program Files\MyProgram\myprogram.exe" "%1"
mycustproto.reg example:
Windows Registry Editor Version 5.00
[HKEY_CURRENT_USER\Software\Classes\mycustproto]
"URL Protocol"="\"\""
#="\"URL:MyCustProto Protocol\""
[HKEY_CURRENT_USER\Software\Classes\mycustproto\DefaultIcon]
#="\"mycustproto.exe,1\""
[HKEY_CURRENT_USER\Software\Classes\mycustproto\shell]
[HKEY_CURRENT_USER\Software\Classes\mycustproto\shell\open]
[HKEY_CURRENT_USER\Software\Classes\mycustproto\shell\open\command]
#="\"C:\\Program Files\\MyProgram\\myprogram.exe\" \"%1\""
C# console application - myprogram.exe:
using System;
using System.Collections.Generic;
using System.Text;
namespace myprogram
{
class Program
{
static string ProcessInput(string s)
{
// TODO Verify and validate the input
// string as appropriate for your application.
return s;
}
static void Main(string[] args)
{
Console.WriteLine("Raw command-line: \n\t" + Environment.CommandLine);
Console.WriteLine("\n\nArguments:\n");
foreach (string s in args)
{
Console.WriteLine("\t" + ProcessInput(s));
}
Console.WriteLine("\nPress any key to continue...");
Console.ReadKey();
}
}
}
Try to run the program first to make sure the program has been placed in the correct path:
cmd> "C:\Program Files\MyProgram\myprogram.exe" "mycustproto:Hello World"
Click the link on your HTML page:
You will see a warning window popup for the first time.
To reset the external protocol handler setting in Chrome:
If you have ever accepted the custom protocol in Chrome and would like to reset the setting, do this (currently, there is no UI in Chrome to change the setting):
Edit "Local State" this file under this path:
C:\Users\Username\AppData\Local\Google\Chrome\User Data\
or Simply go to:
%USERPROFILE%\AppData\Local\Google\Chrome\User Data\
Then, search for this string: protocol_handler
You will see the custom protocol from there.
Note: Please close your Google Chrome before editing the file. Otherwise, the change you have made will be overwritten by Chrome.
Reference:
https://msdn.microsoft.com/en-us/library/aa767914(v=vs.85).aspx
Chrome 13 now supports the navigator.registerProtocolHandler API. For example,
navigator.registerProtocolHandler(
'web+custom', 'http://example.com/rph?q=%s', 'My App');
Note that your protocol name has to start with web+, with a few exceptions for common ones (like mailto, etc). For more details, see: http://updates.html5rocks.com/2011/06/Registering-a-custom-protocol-handler
This question is old now, but there's been a recent update to Chrome (at least where packaged apps are concerned)...
http://developer.chrome.com/apps/manifest/url_handlers
and
https://github.com/GoogleChrome/chrome-extensions-samples/blob/e716678b67fd30a5876a552b9665e9f847d6d84b/apps/samples/url-handler/README.md
It allows you to register a handler for a URL (as long as you own it). Sadly no myprotocol:// but at least you can do http://myprotocol.mysite.com and can create a webpage there that points people to the app in the app store.
This is how I did it. Your app would need to install a few reg keys on installation, then in any browser you can just link to foo:\anythingHere.txt and it will open your app and pass it that value.
This is not my code, just something I found on the web when searching the same question. Just change all "foo" in the text below to the protocol name you want and change the path to your exe as well.
(put this in to a text file as save as foo.reg on your desktop, then double click it to install the keys)
-----Below this line goes into the .reg file (NOT including this line)------
REGEDIT4
[HKEY_CLASSES_ROOT\foo]
#="URL:foo Protocol"
"URL Protocol"=""
[HKEY_CLASSES_ROOT\foo\shell]
[HKEY_CLASSES_ROOT\foo\shell\open]
[HKEY_CLASSES_ROOT\foo\shell\open\command]
#="\"C:\\Program Files (x86)\\Notepad++\\notepad++.exe\" \"%1\""
Not sure whether this is the right place for my answer, but as I found very few helpful threads and this was one of them, I am posting my solution here.
Problem: I wanted Linux Mint 19.2 Cinnamon to open Evolution when clicking on mailto links in Chromium. Gmail was registered as default handler in chrome://settings/handlers and I could not choose any other handler.
Solution:
Use the xdg-settings in the console
xdg-settings set default-url-scheme-handler mailto org.gnome.Evolution.desktop
Solution was found here https://alt.os.linux.ubuntu.narkive.com/U3Gy7inF/kubuntu-mailto-links-in-chrome-doesn-t-open-evolution and adapted for my case.
I've found the solution by Jun Hsieh and MuffinMan generally works when it comes to clicking links on pages in Chrome or pasting into the URL bar, but it doesn't seem to work in a specific case of passing the string on the command line.
For example, both of the following commands open a blank Chrome window which then does nothing.
"c:\Program Files (x86)\Google\Chrome\Application\chrome.exe" "foo://C:/test.txt"
"c:\Program Files (x86)\Google\Chrome\Application\chrome.exe" --new-window "foo://C:/test.txt"
For comparison, feeding Chrome an http or https URL with either of these commands causes the web page to be opened.
This became apparent because one of our customers reported that clicking links for our product from a PDF being displayed within Adobe Reader fails to invoke our product when Chrome is the default browser. (It works fine with MSIE and Firefox as default, but not when either Chrome or Edge are default.)
I'm guessing that instead of just telling Windows to invoke the URL and letting Windows figure things out, the Adobe product is finding the default browser, which is Chrome in this case, and then passing the URL on the command line.
I'd be interested if anyone knows of Chrome security or other settings which might be relevant here so that Chrome will fully handle a protocol handler, even if it's provided via the command line. I've been looking but so far haven't found anything.
I've been testing this against Chrome 88.0.4324.182.
open
C:\Users\<Username>\AppData\Local\Google\Chrome\User Data\Default
open Preferences then search for excluded_schemes you will find it in 'protocol_handler' delete this excluded scheme(s) to reset chrome to open url with default application

Windows Phone 8 IE10 Javascript debugging

IE10 has some wonderful enhancements in the HTML5 compliance area but remains a bear to develop JavaScript HTML5 when running on the WP8 as there is no way to debug the app except console messages.
Is there a remote debugging experience available for IE10 running on WP8 like the WebKit phone browsers have(see my video at http://www.youtube.com/watch?v=GNAjzFpNEj4 for example). When this is in place with a USB cable to desktop Safari debugging Javascript apps on IOS is easy as breakpoints can be set and variables examined in the remote debugger . I am hoping the same capabilities are in IE10 and would appreciate any information on where to enable these very much needed capabilities.
The bad news, that there is no new debug capabilities in comparison to WP7/IE9. Please take a look on How do I debug Internet Explorer on Windows Phone 7? since we are in exactly the same situation on WP8.
What I personally use on daily basis
Debug your app in IE10 Desktop as much as possible
Weinre remote debugger. Demo video. You can use the following app based on Weinre to simplify its usage (no local setup needed) - IeMobileDebugger src or link to Store
Supports
Html traversing
Html node styles, properties, metrics
Reading console output
Executing js on device side from console (including intellisense)
Dynamic script injection - ability to debug live sites
Not supported
js breakpoints
For javascript line by line debugging use aardwolf. Demo with VS integration.
To redirect console trace to Visual Studio output and be able to use console.log("some message") for tracing
index.html:
<script type="text/javascript">
window.console = {
log: function (str) { window.external.Notify(str); }
};
// output errors to console log
window.onerror = function (e) {
console.log("window.onerror ::" + JSON.stringify(e));
};
console.log("Installed console !");
</script>
MainPage.xaml.cs
private void Browser_Loaded(object sender, RoutedEventArgs e)
{
Browser.IsScriptEnabled = true;
// Add your URL here
Browser.Navigate(new Uri(MainUri, UriKind.Relative));
Browser.ScriptNotify += (s, arg) =>
{
Debug.WriteLine(arg.Value);
};
}
FWIW: Windows Phone 8.1 finally supports remote debugging. See http://blogs.msdn.com/b/visualstudioalm/archive/2014/04/04/diagnosing-mobile-website-issues-on-windows-phone-8-1-with-visual-studio.aspx
While not a full solution, Lauri Piispanen's consolelog.js, a nodejs-based remote JS console logger could help you.

Permission denied error while executing shell command from JavaScript

I am trying to run shell command to open notepad from JavaScript. This is how my code looks like:
<script type="text/javascript">
function runNotepad() {
var oShell = new ActiveXObject("Shell.Application");
var commandtoRun = "C:\\WINDOWS\\Notepad.exe";
oShell.ShellExecute(commandtoRun, null, "", "open", "1");
}
</script>
When i try to run this, it throws me an error saying Microsoft JScript runtime error: Permission denied.
I also have set Allow active content to run in files on my computer in IE but still no luck.
Any idea what am i missing here?
Any idea what am i missing here?
No browser would allow JavaScript to arbitrarily start a process. This functionality is not available in Internet Explorer because of the security implications.
This will work if run from other Scripting Hosts, such as cscript, but not Internet Explorer.
You can't run or create native objects inside webpage javascript. The idea is that if someone could do that, then they could create a FileSystem object. Then, while you idly browse their webpage, they play havoc with your file system.
If you need to do this, and have the file saved on the host's machine, save it as an HTML app (*.hta).

Categories