How to do browser automation in javascript natively? - javascript

I am working on a javascript project where I want to perform different operations in browser like:
startBrowser() -> Start the browser(User Input) and opens given URL(User Input)
stopBrowser()-> Kill the specified opened browser.
getLatestURL()-> Fetched last visited URL (Doesn't matter browser is running or it's closed)
deleteAllHistory()-> Delete all the data -> Browser History, cookies, cache, saved passwords, bookmarks etc.
How do I do it without using any 3rd party package?
I have written some code:
function openBrowser(url)
{
//open chrome browser
require('child_process').exec('open ' + url);
}
function killBrowser()
{
//close chrome browser
require('child_process').exec('killall chrome');
}
openBrowser("www.google.com")
killBrowser()
The above code does work like,it opens and close the browser instantly but when I call killBrowser method on already opened browser,it doesnt work.
Can someone help?

Related

Chrome asks if an application should be opened

We have a website that allows the user to download and open a Word file.
Chrome started recently opening an annoying popup when the users downloads the Word
The javascript code called to open the file is
function webDAVOnLineEditionAcm(docURL) {
try {
setTimeout(function(){ ITHit.WebDAV.Client.DocManager.EditDocument(docURL, "/", protocolInstallCallback); }, 5000);
} catch (e) {
console.log(e);
}
}
Is there some solution to tell Chrome to always open that kind of links? It is annoying our users, that need to frequently click that button but also breaks all our acceptance tests...
Short answer, no. This is a security feature to prevent a malicious script from being able to launch local applications or open executable files.
One solution is to educate your users. Show a notice on the page when they click to open that explains how to suppress the prompt.
Another solution is to trigger a download of the file. They can then open that file by clicking on it in the downloads list. They won't be prompted in this case.
Finally, a more involved solution is to process the word document and convert it to HTML so they can be viewed directly on the site. You could then pair this with the download solution to get the original document.

Eel application: download files in Browser

i´m currently using JavaScript and HTML with eel and Python. But unfortunately when I am trying to create a file in the Chrome-Browser window (as an download) over JS i can only download it once.
The second "download" is not working.
-> Chrome just shows this (as it does when it downloads something) but then nothing happens:
When I am using Edge browser or only JS without eel it works perfectly fine!
My JS function that creates the download: (string is a json string that is generated earlier).
var jsonLink = document.getElementById("jsonLink");
jsonLink.download = "exportedToJson.json";
jsonLink.href = "data:application/json;charset=utf-8," + encodeURIComponent(string);
Ok I found a solution:
My chrome browser was blocking more than one download from "localhost:8000". So I had to go to settings and allow more than one download.
Maybe this helps someone :)
Why did I not find this earlier:
When I started my Python script, it calls:
eel.start('index.html', mode='chrome', port=8000) #starting chrome
Which does open a new Chrome Tab without the Tabbar (so i did neither see the tabs nor my favorite sites). Therefore I did not get a notification when chrome stated that download is blocked.
But after starting the eel-local webserver and open localhost:8000 in my normal chrome window, I did get a notification and I was able to allow the downloads.
-> afterwards it also worked in this eel-chrome window.

HTML transient modal window

We have a legacy web application. At various places it opens a window with the help of Privilege Manager on Firefox to get the needed result.
Some of these windows open a Java applet or a PDF document.
The client machines are updating Firefox and Privilege Manager is gone.
What is the easiest way around it?
The problems are :
There must be only one instance of the pop-up at anyone time. This could be done by selecting appropriate window name on window.open() call.
If the window is opened again (by means of user action), it should not reload but just focus to bring it to the foreground (I have seen I can keep a reference to the window on JavaScript to do that)
It basically really must be transient/modal so that the client cannot leave the current page or reload or any other kind of interaction with the parent window (except opening/refocusing the child window) without closing the child window first. I have no idea how to do that.
Do anyone has an idea how to do that?
The client is only Firefox (it works in a special kiosk configuration) on Linux.
I read somewhere that I could somehow write an extension but I am basically clueless about extensions and its API.
Edit1:
Example of (simplified) legacy code. Not really sure if all the permissions were required, but this is it: This function opens a window that stays over the parent window and prevents any interaction from the user with the parent window.
function fWindowOpen(url, name) {
netscape.security.PrivilegeManager.enablePrivilege("UniversalBrowserRead");
netscape.security.PrivilegeManager.enablePrivilege("UniversalBrowserWrite");
netscape.security.PrivilegeManager
.enablePrivilege("CapabilityPreferencesAccess");
netscape.security.PrivilegeManager
.enablePrivilege("UniversalPreferencesWrite");
netscape.security.PrivilegeManager
.enablePrivilege("UniversalPreferencesRead");
netscape.security.PrivilegeManager.enablePrivilege("UniversalFileRead");
netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
window.open(
url,
name,
"screenX=70,dependent=yes,menubar=0,toolbar=0,width=900,height=700,modal=1,dialog=1"
);
}
function fnCapture(){
fWindowOpen("/path/to/document_or_japplet/page","_blank");
}
HTML:
<button value="Capture" property="btnCapture" onclick="javascript:fnCapture();"/>
Edit2: Solution
On a typical extension, on the xul code, define this javascript code:
var dialogExt = {
listener: function(evt) {
// Do work with parameters read through evt.target.getAttribute("attribute_name")
window.openDialog(evt.target.getAttribute("url"), evt.target.getAttribute("name"), evt.target.getAttribute("features"));
}
}
// from examples
document.addEventListener("dialogExtEvent", function(e){ dialogExt.listener(e); }, false, true);
Then, on the web page:
var element = document.createElement("dialogExtElement");
element.setAttribute("url", url);
element.setAttribute("name", name);
element.setAttribute("features", features);
document.documentElement.appendChild(element);
var evt = document.createEvent("Events");
evt.initEvent("dialogExtEvent", true, false);
element.dispatchEvent(evt);
Now, maybe I am missing some security checks to let the code work if it originates from the same host, and how to handle a reference to the document that requested the dialog as means of interaction between the dialog window and it's opener.
The Privilege Manager was deprecated in Firefox 12 and removed in Firefox 17 (briefly restored).
You might want to look into Window.showModalDialog(). However, it is deprecated and is expected to go away within the year, or in 2016 if you go with an extended service release (ESR) of Firefox 38. It may be a temporary solution while you develop an extension.
In order to accomplish the same tasks, you will need to write an extension and ask the user to install it (from Bypassing Security Restrictions and Signing Code, the old information about Privilege Manager):
Sites that require additional permissions should now ask Firefox users to install an extension, which can interact with non-privileged pages if needed.
It is possible to write such an extension using any of the three different extension types:
XUL overlay
Restartless/Bootstrap
Add-on SDK
For the first two types, you would use window.open(). The modal option is in "Features requiring privileges". You will probably also want to look at Window.openDialog().
For the Add-on SDK, you would normally use the open() function in the SDK's window/utils module. Here, again, you will probably want to look at openDialog().
It appears you may be opening content that is supplied from the web in these modal windows. It is unlikely that you will get an extension approved to be hosted on AMO which opens content in such windows which in not included in the add-on release. This does not mean you can not develop the extension and have it installed on your kiosk clients without hosting it on AMO. However, there are additional restrictions in development for Firefox this year which will make this significantly more difficult, see: "Introducing Extension Signing: A Safer Add-on Experience".
You should be able to get similiar window.open behavior, including support for the modal option from the sdk's window/utils module.
You will have to install the onclick listener with a content script, send a message to the addon-main through its port and then open that window from the addon main.

Javascript running only once on Internet Explorer, runs properly when developer tools is open

We have an unusual problem with javascript running on IE 11. I tried it on one of our servers running IE8 and the same problem occurs. However, it runs fine on Chrome and Mozilla.
Here's the code in question:
SetGuideFatningCookie(fid); //set a cookie according to user choice
var validFatningCombo = ValidFatningCheck(); //ask server if user choice is valid using XMLHttpRequest GET request
if(validFatningCombo)
window.location.href = GetGuideTilbehoerURL(); //if valid redirect user to next page
else
popAutoSizeFancy("#GLfancy"); //if not show a fancybox with error text
The user chooses one of 7 choices. Then they click a button that runs the above code. The code sets a cookie containing the user's choice and asks the server if the choice is valid. If valid - we redirect the user and if not, we open a fancybox that contains some error text and two buttons - "Try again"(closes box and they can try again) and "Send us a message"(redirects user to our "ask us a question" page).
The code runs fine the first time the user goes to this process.
However, if they have chosen an invalid choice, they close the fancybox and try to choose another choice and continue -> then the fancy box appears ALWAYS, regardless of what the user chooses.
If they choose a valid choice and continue, get redirected to next page, then come back to this page and choose an invalid choice and press continue -> then they can continue to the next page without fancybox ever coming up.
However, if IE's developer tools are opened, the code runs correct every single time.
I have found many threads describing this is a problem with console.log. I have removed every single reference to console.log from all our .js files. It could be one of the external libraries that we are using, like jquery, modernizr, fancybox and menucool's tooltip library.
Therefore I tried including a console fallback function for IE, like this thread suggests:
Why does JavaScript only work after opening developer tools in IE once?
I am currently trying with this one, and I have tried every single other fallback console replacement from the thred I link to.
if (!window.console) window.console = {};
if (!window.console.log) window.console.log = function () { };
I tried including it:
Somewhere in our .js files
script element in head after loading all our .js files and all external libraries
script element in head before loading all our .js files and all external libraries
Inside $(document).ready(function() {}); , in a script element in head after loading all other js
So far, none of the fallback pieces of code I have tried in any of these 4 locations have solved the problem. It always behaves the same way in IE. I couldn't find another explanation than the "console" one for this problem so far, so if anyone got any insight on it, it would be greatly appreciated.
EDIT: I will include some more info:
The very act of opening Developer Tools removes the unwanted behaviour. No errors are ever shown in console.
I checked the server side to see if the server is getting the call from ValidFatningCheck(); It turns out that the call is made only the first time (or if Developer tools is open - every time) which is rather mysterious since the redirect/fancybox line comes after the server call and it doesn't fail to run, even if it runs wrong.
function ValidFatningCheck(){
var requestUrl = '/Tools.ashx?command=validscreen';
var req = new XMLHttpRequest();
req.open('GET', requestUrl, false);
req.send(null);
var res = "";
if (req.readyState==4)
res = req.responseText;
if(res == "true")
return true;
return false;
}
UPDATE : Problem solved by adding a timestamp to my XMLHttpRequest as multiple replies suggested. I didn't realize XMLHttpRequest uses AJAX so I overlooked it as a probable cause to the problem.
(I put in comments but will make this an answer now as it appears to have solved the problem) get requests are cached by IE but when the developer console is open it does not perform this cache.
three ways to fix:
add a timestamp to the request to trick the browser into thinking it is making a new request each time
var requestUrl = '/Tools.ashx?command=validscreen&time='+new Date().getTime();
set the response header to no-cache
make a POST request as these are not cached
(as pointed out by #juanmendes not ideal you are not editing a resource)

How to open a new window or tab via javascript in windows phone 7 browser

Is it possible to open a new window or tab via javascript in Windows Phone 7 browser?
window.open does not appear to be supported nor does target='_blank'.
Am I missing something here? This basic feature works just fine on iphone and android.
Any ideas on how I can get this working in Windows Phone 7?
On Windows Phone 7 this is not possible programmatically. It's all in the users hand.
To cite a Microsoft employee:
"A user can open a link in a new Tab by tapping and holding the link to
get the context menu but an anchor or scripts request to target a new
window is ignored.
There are several reasons for this:
Cross-window communications are not supported.
Windows Phone only has one instance of the
browser so new "windows" have to be opened as Tab's.
The browser experience is full screen so the user has no good visual cue that they
have moved to a new Tab unless they explicity request it.
Navigating "back" in a new Tab exits the browser which would be
confusing to the user if they did not know a new Tab was created."
If you are trying to add this feature for in-ap browser control, I can suggest you one way.
You have to inject a java-script on every webpage the browser control is able to load the page successfully. In the java-script use window.extern.notify to invoke the ScriptNotify function in your code behind. On the detection of the appropriate message create a new instance of browser control and add it to an array or list. Thereby you can emulate the new tab feature for in-app browser control.
the JS code to be injected may be like this String NEW_TAB_FUNCTION = "window.open = function(__msg){window.external.notify('addnewtab');};";
Which can be injected using browser.InvokeScript("eval", NEW_TAB_FUNCTION);
In ScriptNotify check for addnewtab (keep IsScriptEnabled = True)
void WebBrowser_ScriptNotify(object sender, NotifyEventArgs e)
{
if (e.Value == "addnewtab")
{
//do work here
}
}
Note that I have overridden the window.open function in the JS with a function which will be injected every time on a new webpage in order to get notified of user input.
Also note this works only for WebBrowser Control and not external browser.
My workaround this issue is simple:
window.open
returns null if failed, so in that case I open it in the same window:
var win = window.open(href, '_blank');
if(!win || win==null){
window.location.href = href;
}else{
win.focus();
}
which is a good practice to have a fallback anyway...

Categories