Tutorial for using JavaScript on a Desktop - javascript

I need to do some scripts in java script.
I am working on it but couldn't find a few solutions to a few problems.
First of all I need a GOOD tutorial, but not for an internet page but for a DESKTOP script.
Things couldn't find out like :
1) I wanted a simple message box in order to debug my program, I used:
var name = prompt("What is your name","Type Name Here");
When running it I get error of "Object expected"
2) Couldn't find how to open a file

Based on your comments, I guess that you are attempting to run a JavaScript file directly on Windows. Double-clicking on a .js file in windows will (probably) run it in Windows Script Host.
The prompt() function will not work this way, since WSH provides a completely different API than browser-embedded engines.
The following code should accomplish your intentions. However if you want anything more than a simple popup, HTAs are the only way to do complex GUIs with JScript on the desktop.
var fso, ws, ts;
fso = new ActiveXObject('Scripting.FileSystemObject');
ws = WScript.CreateObject('WScript.Shell');
var ForWriting= 2;
ts = fso.OpenTextFile('foo.txt', ForWriting, true);
ts.WriteLine(new Date().getTime());
ts.Close();
ws.Popup('Wrote to file!');
var ForReading= 1;
ts = fso.OpenTextFile('foo.txt', ForReading, false);
var fileContents = ts.ReadLine();
ts.Close();
ws.Popup('The file contained: ' + fileContents);
WScript.Quit();

I have to ask: why is JavaScript the right tool for the job? Why not use a scripting language intended to be used this way, such as Python, Ruby, Lua, ... etc?
If you are using Microsoft's JScript (and it sounds like you are), look to the MSDN web site for help. The page here looks fairly good. Google can also help with that.
Assuming you don't mind using Java, you could also use the Mozilla Rhino shell. But it doesn't look like there is a standard way of reading from the console in JavaScript. (presumably since this is not something typically required in a JavaScript application...) The built in JavaScript functions in the shell seem fairly basic, but you can read a file.
There area also examples of using Rhino, which may be helpful. You can interface with the Java API to do whatever else you need to do.
Edit: I wrote this answer a long time ago; today I would use node.js. See their learning page.

The latest prerelease of Opera acts as a runtime for JS applications.
They have tutorials describing how to use it.
I used: var name = prompt("What is your name","Type Name Here");
When running it I get error of "Object expected"
Presumably your runtime doesn't implement prompt that in a way that is compatible with those arguments.
2) Couldn't find how to open a file
This depends on the runtime you use. JS itself doesn't have anything built in to read files (or display a prompt). You need an environment that provides those objects.

Related

Kotlin, how can I read a dynamic website as text?

As titled, I'm trying to read the content of sites like this one, which appears to be javascript based.
I tried using plain jdk lib, then jsoup and then htmlunit, but I couldn't get anything useful out of it (I see just the source code or just the title or null):
val url = URL("https://registry.terraform.io/providers/hashicorp/tls/latest/docs/data-sources/certificate")
val connection = url.openConnection()
val scanner = Scanner(connection.getInputStream())
scanner.useDelimiter("\\Z")
val content = scanner.next()
scanner.close()
println(content)
val doc = Jsoup.connect("https://registry.terraform.io/providers/hashicorp/tls/latest/docs/data-sources/certificate").get()
println(doc.text())
WebClient().use { webClient ->
val page = webClient.getPage<HtmlPage>("https://registry.terraform.io/providers/hashicorp/tls/latest/docs/data-sources/certificate")
val pageAsText = page.asNormalizedText()
println(pageAsText)
}
WebClient(BrowserVersion.FIREFOX).use { webClient ->
val page = webClient.getPage<HtmlPage>("https://registry.terraform.io/providers/hashicorp/tls/latest/docs/data-sources/certificate")
println(page.textContent)
}
It should be something easy peasy, but I cant see what's wrong
In order for this to be possible, you need something to execute the JS that modifies the DOM.
It might be a bit overkill depending on the use case, and probably won't be possible if you're on Android, but one way to do this is to launch a headless browser separately and interact with it from your code. For instance, using Chrome Headless and the Chrome DevTools Protocol. If you're interested, I have written a Kotlin library called chrome-devtools-kotlin to interact with a Chrome browser in a type-safe way.
There might be simpler options, though. For instance maybe you can run an embedded browser instead with JBrowserDriver and still use JSoup to parse the HTML, as mentioned in this other answer.
Regarding HtmlUnit:
the page has initially no content, all you see is rendered from javascript magic on the client side using one of this spa frameworks.
It looks like there is some feature check in the beginning that figures out the js support in HtmlUnit does not have all the required features and based on this you only get a hint like "Please enable Javascript to use this application".
You can use
page.asXml()
to have a look at the content trough HtmlUnit's eyes.
You can open an HtmlUnit issue on github but i fear adding support for this will be a longer story.

Most performant way to execute JS within a webpage in Ruby (HtmlUnit, Celerity, PhantomJS, CasperJS ...)

What's the most performant way to execute JS directly after a HTTP request in JRuby? I know about all the test frameworks like HtmlUnit, Celerity, Capybara + PhantomJS == Poltergeist, CasperJS etc. but they're still test frameworks.
What I need is a simple way to execute all JS code which is included in HTML after fetching the URL e.g. by Net::Http.
First of all, it goes with out saying: DON'T DO THIS IN PRODUCTION!
Executing some script that's been pulled from somewhere on the internet is a recipe for disaster. If you're using it as part of your testing infrastructure, it may be of some use but I'd guess that there's a simpler way to solve your problem.
To answer the more general question, here's how you'd initialize a JavaScript engine bundled with JDK 1.6+ (effectively a cut down version of Rhino, although this will change in Java 8 probably):
import javax.script.ScriptEngineManager
import javax.script.SimpleBindings
manager = ScriptEngineManager.new
engine = manager.getEngineByName("JavaScript")
bindings = SimpleBindings.new
bindings['x'] = 1
engine.eval("print(x)", bindings)
Getting your engine to evaluate any dependencies like jQuery is left as an exercise to the user. Have a look at the javax.script JavaDoc.
If you need more control over the evaluation environment you'll have to use Rhino directly, or wait for Nashorn...

Android, Javascript, Rhino, JSON

After long search in repo folders I found rhino1_7R2.jar for Android at http://code.google.com/p/android-scripting/source/browse/rhino/rhino1_7R2.jar Unfortunately 1_7R3 is not there.
The script I'm using uses JSON.stringify function which is not present in 1_7R2. There is the JSON2.js file for Rhino but I don't know the proper way to load it at run time. Documentation and example codes are weak. Should I load it as a string and prepend on the running script? Or there is a better way?
I'm using JavaScript to dynamically evaluate some calculations in a loop. I really want to avoid prepending the JSON2.js every time I call a javascript function. Spent almost one day to find out Rhino has supported JSON object at late version and nobody bothered to port it to Android. Looks like another open source project lacking support.
Should i give up and consider using WebView method? Any ideas?
As I understand, you hava some JavaScript script that you want to run by Rhino. If you want to load another JavaScript file, you can use load function:
load("/your/path/json2.js");
After that call your script can use json2 library.
var testStr = '{"test" : {"a": "aval", "b" : "bval"}}';
var jsonObj = JSON.parse(testStr);
var a = jsonObj.test.a;

WScript.Sleep() ~ WSScript is undefined

I'm trying to follow some example code from microsofts mdn site..
var WshShell = new ActiveXObject("WScript.Shell");
var oExec = WshShell.Exec("calc");
while (oExec.Status == 0)
{
WScript.Sleep(100);
}
WScript.Echo(oExec.Status);
I'm currently writing a javascript/JScript to run a few batch commands. Everything works fine if I don't use WScript.Sleep(). However, If i try to use it, to prevent locking up the browser, i'm getting an error that WScript is not defined.
I figured that I needed to define it myself. However, I have been searching mdn website all day with no luck. This is my first time using any "windows only" products I could be coompletly overlooking something.
If you want to see the documentation I'm looking through it is located here.
http://msdn.microsoft.com/en-us/library/ateytk4a(v=vs.85).aspx
Any help is greatly appreciated.
Thanks,
Freddy
WScript is an object that is defined when the Javascript is run within the Windows Script Host, aka WSH. The object is not available within the Javascript engine in a web browser.
If you are really trying to produce "batch like" files, then you don't need a browser, and I'd say you probably don't want a browser. You can write your code into a .js file and just run it from the cmd.exe prompt or Explorer window with a double-click.
Change the script language from JavaScript to JScript

JavaScript code completition done right?

I've tried some of the editors/IDEs regularly recommended for coding JavaScript (Aptana, WebStorm, ...) but none of them has a satisfying autocomplete functionality. I'm probably spoiled by Microsoft's IntelliSense for .NET. There is some JavaScript-IntelliSense in WebDeveloper, but that seems to be a stripped-down version. The best I've found so far is WebStorm, but its code completition is easily distracted by imported libraries (offering hundreds of suggestions) and identical function names.
Did I miss an editor/IDE that uses refactoring (or something else) to offer proper code completition, so that it really "knowns" what that variable-name stands for, I just put a dot behind? Or is something like this on its way?
I always recommend Komodo Edit from ActiveState (now up to version 6, with support for HTML 5 and CSS3 as well as recent versions of Javascript, PHP, etc.) Note that you may have to install addons for the languages you're working in, but you should find them through the Mozilla-like Addon manager.
Also supports jQuery and even lets you use jQuery (along with vanilla Javascript or Python) in its powerful macro IDE.
Code completion example:
<script type="application/x-javascript">
var obj = {};
obj.personnel = [{firstName:"John", lastName:"Brick", age:43},
{firstName:"Jane", lastName:"Motte", age:26}
];
// now type obj. and code completion immediately offers you "personnel"
// note: file must be saved for the app to find all members of declared
// variables, but I save about every 10 seconds so it's not a problem
</script>
The best I've found so far is
WebStorm, but its code completition is
easily distracted by imported
libraries (offering hundreds of
suggestions) and identical function
names.
This comment confuses me. If you import the libraries, and your code is using them, why is it bad to include the function names in the code completion suggestions? Wouldn't you want to have jQuery's functions included if you're using it?
If you're using Microsoft's IntelliSense with jQuery, does it stick to its guns and only show JavaScript core functions? Sounds limited to me, unable to be smart when I add libraries.
Or is something like this on it's [sic] way?
It sounds to me like you want a clairvoyant interface. I don't think it is on the way anytime soon.
By the way, "it's" == "it is"; "its" is the possessive.

Categories

Resources