RobotFramework - Execute Javascript - javascript

I'm trying to inject my browser with JavaScript Executor function to get back into running instance of a browser. For it, I'm using the keyword "Exectute JavaScript" My code looks like this:
SeleniumLibrary.Execute Javascript JavascriptExecutor js = (JavascriptExecutor) driver; js.executeScript("alert('OK')")
Error looks like this:
JavascriptException: Message: javascript error: Unexpected identifier
(Session info: chrome=92.0.4515.107)
It looks like import for JavaScriptExecutor? How can this be done?

Can you try below code
SeleniumLibrary.Execute Javascript alert('OK')

The alert should be handled with the Handle Alert keyword as you seem to have done already. For returning to earlier browser instance Selenium provides two entities which can be used. You may want to see the Browsers and Windows section of the SeleniumLibrary documentation.
Basic use case is that when opening browser, you'll give it an alias and then use Switch Browser to get back to that browser instance. Within that browser you may have multiple pages open, they can be accessed with normal locators by using Switch Window keyword. For example I would commonly use the window URL as that tends to have at least some unique part in it. If none of the URL, title, or name are unique, by using keyword Get Window Handles returns a list of windows within that browser. In your case, expecting no other windows are opened during the test, the main browser window can be found with argument MAIN.
You may consider this incomplete example and fill in your specifics which you did not provide in the question.
Test 1
Open Browser ${your URL} alias=browser1
# Do whatever triggers the alert
Handle Alert
Switch Window MAIN

Related

Check if html file would open JavaScript alert dialog

I'm wondering if it is possible to, in Java, detect whether or not an HTML file would open an alert dialog if opened in the browser. Preferably headlessly. For example, a file with the below contents were parsed, it would return true.
<html><script>alert("hey")</script></html>
and the below would return true also
<html><iframe src="javascript:alert(1)" onload="alert(2)"></iframe></html>
but the below would return false because it would not open an alert dialog if it were opened in the browser (because none of the code is syntactically correct, and the part that is isn't in a tag).
<html><script>alert;,(123w)</script>alert(1)</html>
I have thought of a way to approach this problem, but it is flawed. Basically, you see if the stringalert(1) is in the file, etc.
The problem with this is that it wouldn't work in cases where that code isn't inside of script tags or tags that make it execute. An example of where it wouldn't work is: The following would return true, even though it wouldn't actually open a popup <html>alert(1)</html>.
This isn't Android by the way. Appreciate your help!
You will need to not only verify if the Alert function is there but check if the JavaScript function would even run. An example of this is if there is a script with an Alert function inside a function that never runs. The Alert function would be there but it would never run. This would give a false positive. So the in the best case you should run the JavaScript in some way to validate the code and to see if the function would ever run.
As Louis pointed out in the comments Option 2 is better in this case as you will need to account for both the DOM and JavaScript's behaviour as both can change if the Alert function runs and how it runs.
Option 1 : Run the JavaScript with Script Engine
You would need some way of separating the HTML from the JavaScript but once you have that you can do this method.
You can run the JavaScript in Java using ScriptEngine. https://docs.oracle.com/javase/8/docs/technotes/guides/scripting/prog_guide/api.html
If you read the API there is a way to create variables and communicate between your Java Program and the JavaScript you are Running.
To capture the context of the Alert you can create a custom JavaScript function that overwrites the Alert function. Inside this custom function you can send the arguments of the function back to your Java Program.
Option 2 : Headless Browser
You can also try to use a headless browser like JBrowserDriver and as you can see you have an Alert interface with getText as a function. For async issue the headless browser has a default amount of time for waiting for the script to complete. If this default amount is not enough you can use the setScriptTimeout to handle it.
http://machinepublishers.github.io/jBrowserDriver/

How to Exit Programatically Created Browser in JScript

I have the following JScript which opens Internet Explorer, navigates to the current users' Lync Response Group Settings page, and clicks on one of the checkboxes found there:
var ie = WSH.CreateObject('InternetExplorer.Application');
url = "https://LyncServer.DOMAIN.co.uk/RgsClients/Tab.aspx",
ie.visible = true;
ie.Navigate(url);
while (ie.readyState != 4) WSH.Sleep(25);
ie.document.getElementById('ctl05_ctl00_ctl04_ctl00_ctl00_ctl01').click();
Once this is done, I want the script to close the browser window.
I tried the following:
ie.exit()
ie.close()
ie.document.exit()
ie.document.close()
But got this error:
Object doesn't support this property or method
TLDR: Use ie.Quit().
This has nothing to do with VBScript vs. JScript. What you call "the JavaScript close command" is the DOM (not JS) method (not "command") of the Window object. Usually the DOM is the thing you manipulate with JS code that runs inside the browser as part of the HTML it's displaying.
This is unrelated to the InternetExplorer automation object. This method describes the Internet Explorer program, not the HTML page that is displayed in it right now. For example, it has a property that controls whether or not you're in "Offline browsing" mode. That's not part of the DOM.
This object has a bunch of other methods and properties which are mostly documented in the MSDN page I linked above - InternetExplorer object. Specifically, it implements the IWebBrowser2 interface which means it implements the IWebBrowser2::Quit method.
Which is, obviously, unrelated to the WSH WScript.Quit(errorCode) method. Their signatures aren't even compatible. The WSH method returns an (optional) error code, the IE method doesn't.

Javascript Alert message runtime error Object Expected

Ok .. this is a strange one as I have NOT seen this before. I have an application that is strictly a Service ... no browser involved ... and all I want to do is use alert(); for debugging. The only problem is that it causes an Object Expected error even if it is a simple alert("Show me!");
Remember ... this code is not attached to any form or browser. So what am I missing? I thought I could use the alert call at any time in Javascript ... Please folks, help a poor programmer out!
Thank you in advance,
Eric
Like praneeth already suggested in his reply, it is a Windows WScript thing, or rather just context in which the script is being run in.
This also works and isn't quite as verbose as what praneeth offered:
WScript.Echo("Hello");
if you are executing this script on a windows machine you can do like this in javascript/Jscript
Var Shell = new ActiveXObject("WScript.Shell");
Shell.Popup("Your Debug message");
The alert() method is one of the JavaScript browser Window object's methods which displays an alert box with a message and an OK button.
The window object represents an open window in a browser. If a document contain frames, the browser creates one window object for the HTML document and one additional window object for each frame.
I believe that in the specified case, the error means that the Window expected object has not been found.
Have you tried window.alert("show me");?
Since alert() is a Window object method.
If you're not running in a browser, you might have better luck using the console.log method - again, it's very hard to tell you specifically what to do without any detail of what environment you're executing the script in.

Silverlight 4 MVVM: Call Javascript function from viewmodel

we have developed an Intranet Management Application with Silverlight 4. We have been asked to add the functionality to call a remote desktop tool which is installed on clients using the Intranet SL App. In an earlier version of the tool written in ASP.NET we just added a Javascript function to the aspx page like this:
function RunShellCommand()
{
var launcher = new ActiveXObject("WScript.Shell");
launcher.Run("mstsc.exe");
}
and called it from ASP.NET.
Now it's clear that SL4 is running in a sandbox and that I cant use the AutomationFactory to create a WScript.Shell object (out of browser mode is not an option).
I thought I could circle around the problem by, again, adding the RunShellCommand javascript method in the aspx page where the SL4 control is hosted and call it via
HtmlPage.RegisterScriptableObject("Page", this);
HtmlPage.Window.Invoke("RunShellCommand", "dummydata");
from my ViewModel. When I run the Application the debugger just skips the RegisterScriptableObject method and quits. Nothing happens.
My question is if am doing something wrong or if this just wont work this way.
Is it possible that I cant do a RegisterScriptableObject from a viewmodel?
EDIT: When I explicitly put a try, catch block around the two methods I get an ArgumentException from the first method stating that the current instance has no scriptable members. When I delete the first method and only run the Invoke, I get a browser error stating that the automation server cant create the object. So is there really no way (except OOB mode) to do this?
Yes, the explanation is correct: you should add at least one method with the ScriptableMember attribute in order that you can use the RegisterScriptableObjectmethod. But it is used only for calling C#-methods from JavaScript.
As far as I see, you want to do the opposite: to call JavaScript code from the Silverlight application. Then you need only one line:
HtmlPage.Window.Invoke("RunShellCommand");
The error automation server cant create the object has nothing to do with Silverlight. I'm sure that if you call the JS function directly - the error will remain.
According to the internet, the reason might be not installed Microsoft Windows Script. Or it is because of security restrictions of the browser.

handling javaScript alerts when running a selenium test?

I am am running some selenium tests(ruby) on my web page and as i enter an invalid characters in to a text box i have the JavaScript throw a alert like so
if(isNaN($(this).val()) || Number($(this).val().valueOf() <=0)){
alert("Please Enter A Number");
}
how can i handle this alert when its made and close the pop up?
i tried to use the wait_for_pop_up() and close() but i think that's only for browser pop up's and not JavaScript alerts.
any ideas?
thanks
The documentation isn't of much help but the Java Docs for Selenium RC seem to show that a getAlert() does exist here. Also this site lists these functions as well:
Processing with Selenium The following commands are available within Selenium for processing Alerts:
getAlert()
assertAlert() assertAlertNotPresent()
assertAlertPresent() storeAlert()
storeAlertPresent() verifyAlert()
verifyAlertNotPresent()
verifyAlertPresent() waitForAlert()
waitForAlertNotPresent()
waitForAlertPresent()
The …AlertPresent() and …AlertNotPresent() functions check for the existence or not of an alert – regardless of it’s content. The …Alert() functions allow the caller to specify a pattern which should be matched. The getAlert() method also exists in Selenium RC, and returns the text from the previous Alert displayed. Similar functions are also available for Confirmations
Selenium intercepts all JavaScript alert() calls (as well as confirm() and prompt()) and handles them itself. You can tell it what you want it to do, and you can find out what happened (excepting during onLoad, as Zugwalt says). You can call isAlertPresent() to check whether an alert was generated or not, and getAlert() to retrieve the text of it. Selenium will even queue them up for you, in case there is more than one (they're retrieved in order). If an alert is generated and you don't call getAlert() to retrieve it, the next Selenium operation will throw an exception. And if you call it when there isn't one, you'll get an exception.
For example (untested, and in C#, but you should get the point):
selenium.GetEval("window.alert('Hi, mom!'); window.alert('Bye, dad!')");
Assert.AreEqual("Hi, mom!", selenium.GetAlert());
Assert.AreEqual("Bye, dad!", selenium.GetAlert());
Assert.IsFalse(selenium.isAlertPresent());

Categories