PowerShell JavaScript Button Click is there any Force Command? - javascript

I want to create automated web tests with PowerShell.
My problem is now that when I click a button with a JavaScript Popup the script hangs at the following line because the event is not finished.
The Popup is loaded but the script hangs.
Is there any force command? Because in the next lines I want to use a Commandlet to click the ok button.
$ie.Document.getElementById("ButtonID")|foreach{$_.Click()} #never finished

There are two approaches to this common problem with automated testing in browsers. Your first option is to redefine all javascript functions with your own mock implementation.
window.alert = function(msg) { log_info(msg); };
window.prompt = function(msg) { return fixture(msg); };
window.confirm = function(msg) { return randomBool; };
Modifying these functions (and others like print, etc) before you start your automation will stop the prompts from blocking the process. But you may still have to worry about security alerts and credential dialogs.
So the second approach is to run a monitoring utility that can interact with the windows on the OS level. Take a look at IEUnit - http://code.google.com/p/ieunit/ It uses a custom activex control called Desktoop (mispelled on purpose) that allows interacting with windows and security alerts from the Windows Script Host.
So you could either use the activex object in powershell or follow this reference - http://msdn.microsoft.com/en-us/magazine/cc163301.aspx for ideas on implementing your own desktoop like module using native powershell features

Related

Call Firefox helper functions from JS

Firefox Web Console offers a screenshot helper function:
:screenshot --selector '#element-id' --dpr 1
Probably a silly question, but is it possible to call this function from JavaScript at my website? Say, I have some button and it calls this:
function downloadScreenshot()
{
if(navigator.userAgent.toLowerCase().indexOf('firefox') === -1)
{ alert("Firefox-only"); return; }
eval(":screenshot --selector '#element-id' --dpr 1");
}
If I try to run this I naturally get SyntaxError: expected expression, got ':'.
So is there some way to call Firefox Web Console API (or whatever) from JS and "tell" it to execute the screenshot command?
Firefox Developer Edition 63.0b10 (64-bit).
I reckon, it is not possible. One of the reasons would be that "malicious" scripts at websites could spam your disc with screenshots taken every millisecond.
You can't. Those helper functions are executed in a totally different context then a web page, with totally different privileges. Here the source code: https://searchfox.org/mozilla-central/source/devtools/shared/screenshot/save.js
So from a web page, you don't have access to them.
The only way to have a similar functionality, is create your own add-on that take the screenshot. Then, from your website, you can check if the add-on is installed, and send to it the command to take the screenshot.

Avoid the detection of "whether Chrome DevTools(console) is open"

Today I see this post
Find out whether Chrome console is open .
#zswang gave the way to detect if Chrome DevTools(console) is open. That's really suprise me, then I began to think is there any way to walk around this detection technique?
There are two way to detect chrome DevTools is open(detail in above post)
Using Object.defineProperty
I can walk around this, it can be assign to another function.I have tried Object.defineProperty=null ,then the detect function die(I know write a mock function is better, here just an example)
Using obj.__defineGetter__ (Object.prototype.__defineGetter__)
Object.prototype.__defineGetter__= null would not break the detection, how to walk around?
Finally, I have to say I don't like to be monitored.Hope there is a proper way to walk around.
There are so many ways to detect the use of DevTools, that it would be difficult to block them all. As DevTools gains new features, there are new ways to detect its use. Any third-party tool to block detection can't be trusted to block 100% of detection techniques.
There is a bug reported to the Chromium team here on the idea of integrating detection blocking directly into Chrome.
Disable javascript
The only way to definitively block any detection of the use of DevTools is to disable javascript. You can still execute javascript in the DevTools console when javascript for a page is disabled. I have found it sufficient to disable javascript immediately after opening DevTools, like this:
Open DevTools Command+Option+J (Mac) or Control+Shift+J (Windows, Linux)
Type the hotkey to open the command menu – Cmd+Shift+P (Mac) or Ctrl+Shift+P (Windows, Linux)
Type dis and hit return to select the Disable Javascript option.
… inspect the website …
Re-enable javascript by evoking the command menu and typing ena and hit return (selecting the Enable Javascript option)
Of course, this method is useless for monitoring malicious code because no code is running when javascript is disabled. But at least it may give you a chance to set breakpoints before re-enabling javascript.
Chrome DevTools Protocol
It may be possible to use the Chrome DevTools Protocol to connect to a separate instance of Chrome and inspect a website without opening DevTools in that instance at all:
The Developer Tools front-end can attach to a remotely running Chrome instance for debugging. For this scenario to work, you should start your host Chrome instance with the remote-debugging-port command line switch:
chrome.exe --remote-debugging-port=9222
Then you can start a separate client Chrome instance, using a distinct user profile:
chrome.exe --user-data-dir=<some directory>
Now you can navigate to the given port from your client and attach to any of the discovered tabs for debugging: http://localhost:9222
The most popular method of detecting if dev tools is open involves invoking console.log() which happens only when devtools is opened.
Below is an example:
var image = new Image();
Object.defineProperty(image, 'id', {
get: function() {
$('#<element_to_remove_on_detection>').remove();
console.clear();
}
});
console.log('%c', image);
In the above case, a new image object is created and the getter is overridden for the 'id'. When console.log is invoked, the getter is called as well.
So basically, any time the getter is called, the website knows that the devtools has been opened because console.log() doesn't get called until devtools is open.
It is a really clever way of detection. Nonetheless, when trying to debug such code, Simply using extension like Resource Override and injecting
console.log = null;
Into the head of the page should stop the website from detecting if devtools is open.
For me, I just added a breakpoint at the top of the offending script, then ran Image = null in the developer console.
I found this solution by googling how websites do that, which brought me this stackoverflow post, I could see in my console a new Image was being logged, so setting Image to null causes an error, which causes the detection to fail.
You could try something like this:
var oldDefineProperty = Object.defineProperty;
Object.defineProperty = function() {
var firstArg = arguments[0];
arguments[0] = _.extend({
get id() {
return firstArg.id;
}
}, arguments[0]);
return oldDefineProperty.apply(this, arguments);
}
var element = new Image();
element.id = "something";
Object.defineProperty(element, 'id', {
get: function() {
alert("detected");
}
});
console.log('%cHello', element);
<script src="http://underscorejs.org/underscore-min.js"></script>
This seems to prevent the alert from showing for me. I'm using the _extend function from Underscore. I don't know if I'm missing anything but just playing around.
As for __defineGetter__, this was deprecated so you'd expect this not to be used.

Log JavaScript console into a log file with Firefox

We have a web application which runs in a kiosk mode Firefox, using the RKiosk extension to achieve this. We suspect that we have a very rare error in the system which yields in a JavaScript error. However because we can't access the JavaScript console we can't examine the log.
I'm searching for an option to make Firefox log all JavaScript console messages into a file regardless of the tab and page opened. I can't seem to find any extension for this. I'm already using log4javascript which sends errors back to the server, but it seems that our application crashes in a way that it skips the logging altogether.
Writing to a file sounds like a tedious task to me. It requires privileges that browser code doesn't normally have and you'd have to negotiate with an add-on you'd have to write in order to access file I/O.
From what I understand your issue is
I'd like to make Firefox log all errors
There are several approaches we can do to tackle this
First approach - log everything to localStorage too:
Now, rather than writing to an actual file, you can write to localStorage or IndexedDB instead.
localStorage["myApplog"] = localStorage["myApplog"] || "";
var oldLog = console.log;
console.log = function(){
oldLog.apply(console,arguments); // use the old console log
var message = "\n "+(new Date).toISOString() + " :: "+
Array.prototype.join.call(arguments," , "); // the arguments
localStorage["myApplog"] += message;
}
This is rather dirty and rather slow, but it should get the job done and you can access the log later in local storage. LocalStorage has a ~5MB limit if I recall correctly which I think is enough if you don't go crazy with logging. You can also run it selectively.
Second approach - log only errors
This is similar to what Pumbaa80 suggested. You can simply override window.onerror and only log errors.
// put an empty string in loggedWinErrors first
var oldError = window.onerror || function(){};
window.onerror = function(err,url,lineNumber){
oldError.call(this,err,url,lineNumber);
var err ="\n Error: (file: " + url+", error: "+err+", lineNumber: "+lineNumber+")");
localStorage["loggedWinErrors"] += err;
}
Third and drastic approach - use a VM.
This is the most powerful version, but it provides the most problematic user experience. You run the kiosk in a virtual machine, you detect an uncaught exception - when you do you freeze the machine and save its state, and run a backup VM instead. I've only had to do this when tackling the most fearsome errors and it's not pretty. Unless you really want the whole captured state - don't do this.
Really, do the extension before this - this is tedious but it gets very solid results.
In conclusion, I think the first approach or even just the second one are more than enough for what you need. localStorage is an abstracted storage that web pages get for saving state without security issues. If that's not big enough we can talk about an IndexedDB solution.
It all really depends on the use case you have.
You can use XULRunner...a Mozilla runtime environment for XUL applications. It uses Gecko like Firefox and:
You can access the file system or using the SQLite database to store logs.
You can render your kiosk in fullscreen mode without using extensions.
Have you tried jserrorcollector? We are using it and it works fine (only in Firefox). It's only for Java.
// Initialize
FirefoxProfile ffProfile = null;
ffProfile = new FirefoxProfile();
JavaScriptError.addExtension(ffProfile);
// Get the errors
List<JavaScriptError> jsErrors = JavaScriptError.readErrors(webDriver);
More information: https://github.com/mguillem/JSErrorCollector
Have you considered remote logging?
I commonly assign window.onerror to do send a request to a webserver storing the details of the error remotely. You could do the same with console.log if you preferred.
Try the following console export. It is a plugin for Firebug of Firefox. It's quite handy.
http://www.softwareishard.com/blog/consoleexport/
If you are able/willing to switch from Firefox to Chrome or Opera you would be able to use the Sandboxed Filesystem API to write a local file. See:
http://www.html5rocks.com/en/tutorials/file/filesystem/
http://caniuse.com/filesystem
Start in kiosk mode using chrome.exe --kiosk <url>
You would then want to disable Alt-F4 and Ctrl-Alt-Del which on Windows can be done with several third-party tools like Auto Hotkey (Disable Ctrl-Alt-Del Script).
You could use a remote logging script like Qbaka. It catches every JS error and sends it to the Qbaka server. There you can login and see all JS errors. Qbaka stores the exact error message, the script, line number, stack trace and the used browser for each error message.

How do I turn off the console logging in App Engine Channel API?

I've implemented the Channel API w/ persistence. When I make a channel and connect the socket (this is on the real app, not the local dev_appserver), Firebug goes nuts with log messages. I want to turn these off so I can see my OWN logs but cant find any documentation on how to disable the Channel API console logging.
one thing I'm probably doing differently than most is that I'm connecting cross-domain... which the Channel API supports (note the first message in the stream... if you can view that pic)
Does anyone know?
UPDATE
I finally realized that my code was creating two channels and trying to open/connect them both at the same time... and that was why I was getting a flood of messages. I didn't mean to do this (I know the rules: https://developers.google.com/appengine/docs/python/channel/overview#Caveats )... it was a bug... and once I fixed it, the messages went back to manageable level.
yay
There doesn't appear to be a way to shutoff the Firebug timeStamp log. One way to solve this problem is to edit the code and remove this functionality yourself:
Unpack the extension to a directory in your Mozilla Firefox Profile:
Change directory to your Firefox profile extensions directory. On Ubuntu, this would be something like this:
cd ~/.mozilla/firefox/{random-string}/extensions/
The Firebug extension is identified by firebug#software.joehewitt.com.xpi. Create a new directory of the same name, but without the .xpi, and move the XPI into that directory:
mkdir firebug#software.joehewitt.com
mv firebug#software.joehewitt.com.xpi firebug#software.joehewitt.com
Next, change directories to your newly created Firebug directory, and unpack the extension:
cd firebug#software.joehewitt.com
unzip firebug#software.joehewitt.com.xpi
All of the files should be unpacked so that the extension's directories are in the current directory. Your file structure will look something like this:
$: ~/.mozilla/firefox/{random-string}/extensions/firebug#software.joehewitt.com$ l
chrome.manifest defaults/ firebug#software.joehewitt.com.xpi install.rdf locale/ skin/
content/ docs/ icons/ license.txt modules/
$: ~/.mozilla/firefox/ghlfe0bb.ff5.0/extensions/firebug#software.joehewitt.com$
Open consoleExposed.js in your text editor:
Next, change to the content/firebug/console directory:
cd content/firebug/console
Edit the consoleExposed.js file using your favorite editor:
vim consoleExposed.js
Disable console.timeStamp:
On or near line 215, you'll see the following function:
console.timeStamp = function(label)
{
label = label || "";
if (FBTrace.DBG_CONSOLE)
FBTrace.sysout("consoleExposed.timeStamp; " + label);
var now = new Date();
Firebug.NetMonitor.addTimeStamp(context, now.getTime(), label);
var formattedTime = now.getHours() + ":" + now.getMinutes() + ":" +
now.getSeconds() + "." + now.getMilliseconds();
return logFormatted([formattedTime, label], "timeStamp");
};
Right after the first curly-brace, force the function to return nothing:
console.timeStamp = function(label)
{ return ; // disable timestamp by returning
label = label || "";
if (FBTrace.DBG_CONSOLE)
Restart Firefox and enjoy a world without timeStamp:
After the edits, restart Firebug. You should no longer see the log messages for timeStamp in your console.
On the Development server, when using the ChannelAPI, it essentially degrades into a polling implementation instead of using Comet/long-polling. Thus, in your debugger, you see an endless stream of HTTP requests made to the server to continuously and methodically check for updates.
In essence, these are just AJAX requests, or as Firebug would like to think of them, XMLHttpRequests.
Since your browser is responsible for making these requests, the only way to disable them is to click the small arrow on "Console" in Firebug and uncheck the option for logging XMLHttpRequests.
Of course, this also disables logging for all of your other XMLHttpRequests. But it's a small price to pay for the clarity and serenity of a quiet, well-behaved JavaScript console.
For more helpful information on how to make the most of Firebug, see Firebug Tips and Tricks.
NOTE: This works for both users of the Python SDK as well as the Java SDK. (or Go SDK, assuming it has an equivalent ChannelAPI). This is not limited to only Python Appengine.
UPDATE:
From getFirebug:
Creates a time stamp, which can be used together with HTTP traffic timing to measure when a certain piece of code was executed.
The console.timeStamp method was released in Firebug 1.8.0. The same technique described above can also override this Firebug logging method.
console.timeStamp("This is the type of console logging statement that Google is using!");
The above logging statement would produce the olive text. This method can be disabled using the same techniques which were described in the previous section.
However, Google loads the console object inside of a closure, which means that, once Google's code is initialized, the ChannelAPI object has it's own copy of the console object.
In order to disable console.timeStamp, one would need to disable it as the very first action before anything else loads or runs. in other words, we would need to ensure that Google only gets its hands on the disabled console.timeStamp method.
For best results, load this code above the /_ah/channel/jsapi script tag to ensure the console.timeStamp method is disabled before jsapi loads:
if(window.console) console.timeStamp = function(t) { };
NOTE: Because Google invokes Firebug logging in this manner, the only solution may very well in fact require a bug report or feature request that would allow for programmatically disabling this level of logging. Alternatively, the Firebug team could provide a new version of Firebug that includes the ability to explicitly disable timeStamp log statements, similar to how they've done so with Errors, Warnings, XMLHttpRequests, and other log levels.

Chrome API: Get Window Type

I'm working on a project and run into an issue where I need to distinguish a chrome app window from normal ones. (Specifically I'm using the --app=URL from a bash script) Because of the way things are setup, I have to have run a js script on all windows, but only do something if they are an app window. It seems that the API listed here is what I need to distinguish one window from another, but all I've managed to get are errors saying that a function or object is undefined. So how am I suppose to get the window type from the API with something like window.type?
Additionally, if you know of some other way to tell the difference between chrome windows if they are an app window or not, then that would also work. I really just need to be able to do:
if (window is app) //I don't really care how it's done
{
doSomething();
}
More information:
Tried in both Chrome and Chromium (both fully updated)
Using Ubuntu 18.04
JavaScript is running in the app window and not an extension (not developing an extension)
Can you try the following. In your console
windowType=window.location.host
It should return if you are in app window it will return as "app". Using this you can write your logic
if (windowType === 'app' ) //I don't really care how it's done
{
doSomething();
}
Hope it helps.
Doing windowType.window.location.host returned not the type of window but rather the url provided with the --app=url flag in my bash script. This means that if you open a normal window and go to the same url as provided in the app window, both would return the same url. However, since the normal window would be the same content just a different window type, the JavaScript code that I need to run on the webpage is the same, thus I would want it to run on both windows. So this solution works for me, but for anyone else who is looking for a window specific identifier, and not just a url, I suppose that is still up in the air.
(Thanks Ragavan Rajan)

Categories

Resources