vb.net - Run JS from HTML - javascript

I'm trying to run a JS code same as I would run it from console on webpage.
In code below "myhtml" is string with HTML from page I want to get value of #green
Simpliest answer would be to use webbrowser, but I can't as I'm not working with single-threaded application (so I'd get errors obviously).
The "myhtml" has external scripts that need to be loaded, so answer I'm looking is something like webbrowser that I can use in multithreaded application.
Code I've tried (changed JScript with HTML in js.Language):
Dim js As MSScriptControl.ScriptControlClass = New MSScriptControl.ScriptControlClass()
js.AllowUI = False
js.Language = "HTML"
js.Reset()
js.AddCode("myhtml")
Dim parms As Object() = New Object() {11}
Dim result As Integer = CInt(js.Run("alert(document.getElementById('green').value)", parms))
MsgBox(result)
With result of:
A script engine for the specified language can not be created.

Related

What does execute_script() in Selenium does

browser.execute_script("window.open('about:blank', 'tab2');")
browser.switch_to.window("tab2")
browser.get('http://bing.com')
I was searching online ways to open a new tab using selenium in python, and the method of ctrl + t wasn't working on chrome so I stumbled on the above piece of code, however I am not able to understand what 'excute_script' does.
execute_script method allows to execute JavaScript passed as string argument
Note that you can pass data from Python code into JavaScript code using arguments, e.g.
hello = "Hello"
friends = " friends"
browser.execute_script('alert(arguments[0], arguments[1]);', (hello, friends))
execute_script()
execute_script() synchronously executes JavaScript in the current window/frame.
execute_script(script, *args)
where:
script: The JavaScript to execute
*args: Any applicable arguments for your JavaScript.
This method is defined as:
def execute_script(self, script, *args):
"""
Synchronously Executes JavaScript in the current window/frame.
:Args:
- script: The JavaScript to execute.
- \\*args: Any applicable arguments for your JavaScript.
:Usage:
::
driver.execute_script('return document.title;')
"""
if isinstance(script, ScriptKey):
try:
script = self.pinned_scripts[script.id]
except KeyError:
raise JavascriptException("Pinned script could not be found")
converted_args = list(args)
command = None
if self.w3c:
command = Command.W3C_EXECUTE_SCRIPT
else:
command = Command.EXECUTE_SCRIPT
return self.execute(command, {
'script': script,
'args': converted_args})['value']
Examples
A couple of examples:
To open a new blank tab:
driver.execute_script("window.open('','_blank');")
To open a new tab with an url:
driver.execute_script("window.open('https://www.google.com');")
To retrieve the page title:
driver.execute_script('return document.title;')
To scroll inti view an element:
driver.execute_script("arguments[0].scrollIntoView(true);",element)
References
You can find a couple of relevant detailed discussions in:
What does arguments[0] and arguments[1] mean when using executeScript method from JavascriptExecutor interface through Selenium WebDriver?
What is JavaScriptExecutor in Selenium?

JavaScript Exception in HtmlUnit when clicking at google result page

I want to use HtmlUnit (v2.21) to get some search result pages from google. This requires me to click on "people also looked for" link when searching for a person (right side, see example link), which triggers some JavaScript and changes the content of the current page. But this gives me an JavaScript Wrapper Exception (see below).
Clickable example link: https://www.google.de/search?ie=UTF-8&safe=off&q=nicki+minaj
Simple TestCase with errors:
String url = "https://www.google.de/search?ie=UTF-8&safe=off&q=nicki+minaj";
WebClient client = new WebClient(BrowserVersion.BEST_SUPPORTED);
HtmlPage page = client.getPage(url);
HtmlElement link = page.getFirstByXPath("//a[#class='_Zjg']");
HtmlPage newPage = link.click(); //throws exception
this.storeResultFile(newPage.asXml(), "test");
client.close();
Result:
net.sourceforge.htmlunit.corejs.javascript.WrappedException: Wrapped java.lang.NullPointerException
at net.sourceforge.htmlunit.corejs.javascript.Context.throwAsScriptRuntimeEx(Context.java:2053)
at com.gargoylesoftware.htmlunit.javascript.JavaScriptEngine.doProcessPostponedActions(JavaScriptEngine.java:947)
at com.gargoylesoftware.htmlunit.javascript.JavaScriptEngine.processPostponedActions(JavaScriptEngine.java:1012)
at com.gargoylesoftware.htmlunit.html.DomElement.click(DomElement.java:799)
at com.gargoylesoftware.htmlunit.html.DomElement.click(DomElement.java:742)
at com.gargoylesoftware.htmlunit.html.DomElement.click(DomElement.java:689)
I stored the xml of the "page" object and made sure that the XPath expression is valid and has results.
Anybody got any ideas?
Looks like the JavaScript-Engine (based on Rhino) is very easy to upset and quits on some script-issues, where other browsers are still able to run the script.
I dont know if there is a mistake in the scripts from google, but these two lines solved it for me:
JavaScriptEngine engine = client.getJavaScriptEngine();
engine.holdPosponedActions();
Nevertheless, when running multiple htmlunit-objects in multiple threads it is still possible to get accross this error. This is more a workaround than a solution.

Does anyone knows how to import new classes when using Javascript instead of Groovy as default scripting language in SoapUI?

I have a important piece of code that modifies my requests written Javascript, but i want to add an external jar and use it from the scripts, any suggestions? It's defined a sort of import function or something like that?
In order to use your own jars in Setup Script in SOAPUI with javascript language you must do the next steps:
With SOAPUI closed, copy your jars to SOAPUI_HOME/bin/ext.
Start SOPAUI
On the project properties select Javascript for Script Language property.
Then in the Setup Script you have to reference the full package for your java classes like (I put a sample where I decode a base64 string):
java.lang.System.out.println("-----------");
java.lang.System.out.println("SAMPLE INIT");
java.lang.System.out.println("-----------\n");
var obj = new org.apache.commons.codec.binary.Base64();
var stringb64 = new java.lang.String("dGVzdA==")
var dataDecoded = obj.decodeBase64(stringb64.getBytes());
java.lang.System.out.println("RESULT " + new java.lang.String(dataDecoded) + "\n");
java.lang.System.out.println("-----------");
java.lang.System.out.println("SAMPLE END");
java.lang.System.out.println("-----------");
If you run soapui from .bat you can see the system out on the cmd:

calling a JavaScript function with HTMLUnit

I'm trying to call the function showPage('3'); of this page, for use the page source code after. I tried to do with htmlUnit like so:
WebClient webClient = new WebClient();
webClient.waitForBackgroundJavaScriptStartingBefore(10000);
HtmlPage page = webClient.getPage("http://www.visittrentino.it/it/cosa_fare/eventi/risultati?minEventDate=09012014&maxEventDate=31012014&tp=searchForm.thismonth&ltp=gennaio");
String javaScriptCode = "showPage('3');";
ScriptResult result = page.executeJavaScript(javaScriptCode);
result.getJavaScriptResult();
System.out.println("result: "+ result);
But it's not working.
It prints out:
result: net.sourceforge.htmlunit.corejs.javascript.Undefined#a303147
and other 10000 warnings. What am I doing wrong? I need to change the page of this site for do some crawling on the source code. Is there another way (and maybe more easier) for calling jsp-function from Java code and then navigate in the source of the page?
Thank you for any help, have a nice day.
You print the ScriptResult object not the content of the page,change the SOP code to result.getNewPage()

WP8 App misbehaving due to StreamWrite in JavaScript

I would like to save the results calculated on html page in a textfile using javascript.
<script type="text/javascript">
window.onload = function () {
var sw : StreamWriter = new StreamWriter("HTML_Results.txt");
sr.Write('xyz");
*** calculations ******
sr.Write (result);
}
</script>
by doing this, my WP8 App is misbehaving and not displaying images as usual. This app is an Image Fader (calculates FPS).
Also tried:
StreamWriter sr;
try {
sr = new StreamWriter("\HTML5\HTMLResults.txt");
sr.Write("xyz");
File.SetAttributes("HTML5\HTMLResults.txt", FileAttributes.Hidden);
} catch(IOException ex) {
console.write ("error writing"); //handling IO
}
The aim is to:
Extract calculated values of several html pages(after getting loaded
one by one) in a single text file.
A Resultant HTML that reads this
text file and displays results in a tabular format.
Is there a better way to this job or the above can be rectified and used? Appreciate help.
Perhaps I've misunderstood your code but it looks like you're trying to write Java within JavaScript scripting tags. You cannot write Java in an HTML document. As far as I know, client-side JavaScript (which given your <script> tags is I guess what you're trying to write) can't perform the kind of file I/O operations you seem to want here.
You need to use Node JS to use JavaScript for something like that and then you're talking server-side. The closest you can get on client-side is using the new localStorage feature in HTML5 (not supported by all browsers).

Categories