The offline version repl.it - javascript

Not sure if I am putting my question correctly - Is it possible to have an offline version of repl.it (only JavaScript required), so that it can be used without internet access?

If you're looking to install a way to run a JavaScript REPL on your local machine, you have two options:
Open your browser's console as usual. Lack of internet doesn't make it any less JavaScripty.
Install NodeJS

If you have a text editor that can run a dos command, you can use CScript.exe, the windows version of a javascript engine. Though beware, that this is not ES5 compatible, and there is no browser object. Writing to stdout can be done using CScript.Echo()
I use TextPad which has a tools configuration, in which you can set the CScript path (find it in your windows system directory).

I wonder why can't you do to create your own REPL instead, you just have to create a new window.open("", "_Jres", "", "false") you can also have window.open("", "_self") to replace the current document.
<!DOCTYPE html>
<html>
<head><title>Js Execute</title></head>
<body>
<textarea id="code" rows="10" cols="50">
//write your code here
alert("Clicking OK will write heading 1 in the new window");
document.write("<h1>heading 1</h1>");
</textarea>
<br/>
<button onclick="Execute()">Click To execute the above written JS</button>
<script>
function Execute() {
var win2 = window.open("", "_Jres", "", "false");
var content = document.getElementById("code");
var datacode = content.value;
console.log(datacode);
var hbody = "<script>" + datacode + "</" + "script>";
win2.document.writeln(hbody);
}
</script>
</body>
</html>

Related

Open Explorer window from Website, on mounted drives, including javascript in the link reference to generate the path

In addition to the question here:
Open Explorer window from Website
I'm also having trouble with this, especially because I need to integrate a function into the link that eventually will open in file explore.
Bacially, we have a very simple intranet webpage, to control our cases etc.
Each case has some files in in a folder on the server, but to avoid to many subfolders in one folder, we split them in groubs of 200!
\ip\fileserver\cases\"split-folder"\subfolder
I what to open the folder clicking on the case on our webpage.
The split-folder..is defined in ranges with case-numbers for evey 200 cases (sager in danish)
Like this
\25000-25199\25001
\25200-25399\25399
\25400-25599\25422 or 25555 etc . .
The math to calculate the "split-folder" is simple enough with a script but getting this into a link that will open file explore is not that easy.
<!DOCTYPE html>
<html>
<body>
<button onclick="myFunction(25555)">Try it</button>
<p id="sagslink"></p>
<script>
function myFunction(sagnr) {
var a = Math.floor(sagnr/200)*200
var b = Math.floor(a+199);
var x = "file://///192.168.15.133/Filserver2016/sager/" + a + '-' + b + "/"+sagnr;
document.getElementById("sagslink").innerHTML = x;
}
</script>
Simple link that Works in IE..but not in firefox og chrome.
sager-full-path
But I can not generate a useful link merging the to!
I have tried evey possible way described here to no awail:
JavaScript function in href vs. onclick
Perhaps I need to revice the function to give the actual link in sted. I also don't what a button but just a generat CASE-Number...that serves as link!
Further more! We mount \\192.168.1.133\Fileserver2016 as Z:
So for our various programs, that use the Z drive path, I would like to open file-explore with the mount path and not the ablosoute path.
We can use IE if nessarry..but I would like i to work on firefox and chrome also
Can this be done!
Ok. So we got it working...sort of ;O)
Our intranet webpage runs in ASP
So the code runs serverside.
Here is the code that works in IE-11.
<%
strSagsNR = rsSag("sagsNR")
Function folderlink(FSagsNR)
a = int(strsagsNR/200)*200
b = int(a+199)
folderlink = "file:///Z:/sager/" & a & "-" & b & "/" & strSagsNR
End Function[enter image description here][1]
%>
To ensure the solution works properly locally and when connected with VPN.
It's necessary to add the server ip to IE-11 Internet security - local Intranet - Webplaces - Advanced
as BOTH FILE AND HTTP! See image.
Security setting in IE
Then you should avoid the remark about this file is dangerous and may harm you computer, and File explore will pop up on the correct path ;O)
I have not found any solution for Chrome or Firefox.

Call js function from python [duplicate]

I am working on a web-scraping project. One of the websites I am working with has the data coming from Javascript.
There was a suggestion on one of my earlier questions that I can directly call the Javascript from Python, but I'm not sure how to accomplish this.
For example: If a JavaScript function is defined as: add_2(var,var2)
How would I call that JavaScript function from Python?
Find a JavaScript interpreter that has Python bindings. (Try Rhino? V8? SeaMonkey?). When you have found one, it should come with examples of how to use it from python.
Python itself, however, does not include a JavaScript interpreter.
To interact with JavaScript from Python I use webkit, which is the browser renderer behind Chrome and Safari. There are Python bindings to webkit through Qt. In particular there is a function for executing JavaScript called evaluateJavaScript().
Here is a full example to execute JavaScript and extract the final HTML.
An interesting alternative I discovered recently is the Python bond module, which can be used to communicate with a NodeJs process (v8 engine).
Usage would be very similar to the pyv8 bindings, but you can directly use any NodeJs library without modification, which is a major selling point for me.
Your python code would look like this:
val = js.call('add2', var1, var2)
or even:
add2 = js.callable('add2')
val = add2(var1, var2)
Calling functions though is definitely slower than pyv8, so it greatly depends on your needs. If you need to use an npm package that does a lot of heavy-lifting, bond is great. You can even have more nodejs processes running in parallel.
But if you just need to call a bunch of JS functions (for instance, to have the same validation functions between the browser/backend), pyv8 will definitely be a lot faster.
You can eventually get the JavaScript from the page and execute it through some interpreter (such as v8 or Rhino). However, you can get a good result in a way easier way by using some functional testing tools, such as Selenium or Splinter. These solutions launch a browser and effectively load the page - it can be slow but assures that the expected browser displayed content will be available.
For example, consider the HTML document below:
<html>
<head>
<title>Test</title>
<script type="text/javascript">
function addContent(divId) {
var div = document.getElementById(divId);
div.innerHTML = '<em>My content!</em>';
}
</script>
</head>
<body>
<p>The element below will receive content</p>
<div id="mydiv" />
<script type="text/javascript">addContent('mydiv')</script>
</body>
</html>
The script below will use Splinter. Splinter will launch Firefox and after the complete load of the page it will get the content added to a div by JavaScript:
from splinter.browser import Browser
import os.path
browser = Browser()
browser.visit('file://' + os.path.realpath('test.html'))
elements = browser.find_by_css("#mydiv")
div = elements[0]
print div.value
browser.quit()
The result will be the content printed in the stdout.
You might call node through Popen.
My example how to do it
print execute('''function (args) {
var result = 0;
args.map(function (i) {
result += i;
});
return result;
}''', args=[[1, 2, 3, 4, 5]])
Hi so one possible solution would be to use ajax with flask to comunicate between javascript and python. You would run a server with flask and then open the website in a browser. This way you could run javascript functions when the website is created via pythoncode or with a button how it is done in this example.
HTML code:
<html>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
function pycall() {
$.getJSON('/pycall', {content: "content from js"},function(data) {
alert(data.result);
});
}
</script>
<button type="button" onclick="pycall()">click me</button>
</html>
Python Code:
from flask import Flask, jsonify, render_template, request
app = Flask(__name__)
def load_file(file_name):
data = None
with open(file_name, 'r') as file:
data = file.read()
return data
#app.route('/pycall')
def pycall():
content = request.args.get('content', 0, type=str)
print("call_received",content)
return jsonify(result="data from python")
#app.route('/')
def index():
return load_file("basic.html")
import webbrowser
print("opening localhost")
url = "http://127.0.0.1:5000/"
webbrowser.open(url)
app.run()
output in python:
call_received content from js
alert in browser:
data from python
This worked for me for simple js file, source:
https://www.geeksforgeeks.org/how-to-run-javascript-from-python/
pip install js2py
pip install temp
file.py
import js2py
eval_res, tempfile = js2py.run_file("scripts/dev/test.js")
tempfile.wish("GeeksforGeeks")
scripts/dev/test.js
function wish(name) {
console.log("Hello, " + name + "!")
}
Did a whole run-down of the different methods recently.
PyQt4
node.js/zombie.js
phantomjs
Phantomjs was the winner hands down, very straightforward with lots of examples.

evaluate system command or python script in firefox browser using javascript

May be duplicate.
I would like to write javascript which can execute linux command in firefox (seems to be impossible but asking with hope)
from googling, found that it is possible for IE through "ActiveXObject".
here is sample code:
<SCRIPT type="text/javascript" LANGUAGE="JavaScript">
function executeCommands(inputparms)
{
// Instantiate the Shell object and invoke
its execute method.
var oShell = new ActiveXObject("Shell.Application");
var commandtoRun = "C:\\Winnt\\Notepad.exe";
if (inputparms != "")
{
var commandParms = document.Form1.filename.value;
}
// Invoke the execute method.
oShell.ShellExecute(commandtoRun, commandParms,
"", "open", "1");
}
</SCRIPT>
So, Is there any equivalent of ActiveXObject in javascript for mozilla apps?
I'm quite new to javascript so please, correct mistakes if any.
Thanks!
In a Firefox add-on you can use nsIProcess. Something along these lines:
var file = Components.classes["#mozilla.org/file/local;1"]
.createInstance(Components.interfaces.nsILocalFile);
file.initWithPath("C:\\Winnt\\Notepad.exe");
var process = Components.classes["#mozilla.org/process/util;1"]
.createInstance(Components.interfaces.nsIProcess);
process.init(file);
process.runAsync(["c:\\file.txt"]);
This API is only accessible to privileged code of course.
No, it's not possible to run arbitrary, native commands on the client's machine.

How can I run a local Windows Application and have the output be piped into the Browser

I have Windows Application (.EXE file is written in C and built with MS-Visual Studio), that outputs ASCII text to stdout. I’m looking to enhance the ASCII text to include limited HTML with a few links. I’d like to invoke this application (.EXE File) and take the output of that application and pipe it into a Browser. This is not a one time thing, each new web page would be another run of the Local Application!
The HTML/java-script application below has worked for me to execute the application, but the output has gone into a DOS Box windows and not to pipe it into the Browser. I’d like to update this HTML Application to enable the Browser to capture that text (that is enhanced with HTML) and display it with the browser.
<body>
<script>
function go() {
w = new ActiveXObject("WScript.Shell");
w.run('C:/DL/Browser/mk_html.exe');
return true;
}
</script>
<form>
Run My Application (Window with explorer only)
<input type="button" value="Go"
onClick="return go()">
</FORM>
</body>
Have the executable listen on a port following the HTTP protocol.
Then have the web page make AJAX-style HTTP requests to the local port with JAvascript.
The executable returns text.
The web page updates itself through DOM manipulation in Javascript.
Yes, this works. It is happening 5 feet away from me right now in another cubicle.
This is called CGI
Your already using WScript to launch, it can also read StdOut.
<html>
<head>
<script type="text/javascript">
function foo() {
var WshShell = new ActiveXObject("WScript.Shell");
var oExec = WshShell.Exec("ipconfig.exe");
var input = "";
while (!oExec.StdOut.AtEndOfStream) {
input += oExec.StdOut.ReadLine() + "<br />";
}
if (input)
document.getElementById("plop").innerHTML = input;
}
</script>
</head>
<body onload="foo();">
<code id="plop"></code>
</body>
</html>
It would be easier to have your EXE create a temp file containing the HTML, then just tell Windows to open the temp HTML file in the browser.

How do I download JavaScript string as a file

Application requests KML data through AJAX from server. This data is stored in javascript variables, and displayed in Google Earth plugin.
In javascript, how do I provide a link to download the KML data stored in javascript variable (as a string) without requiring a request back to server?
This link:
http://forum.mootools.net/viewtopic.php?id=9728
suggests the use of data URI, but that probably won't work across enough browsers for my needs. Probably simplest just to go back to server to get data again for download, but curious if anyone has pulled this off with javascript.
This will work! It works for me.
enter link description here
`function download(filename, text) {
var element = document.createElement('a');
element.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(text));
element.setAttribute('download', filename);
element.style.display = 'none';
document.body.appendChild(element);
element.click();
document.body.removeChild(element);
}
// Start file download.
download('hello.txt','This is the content of my file ');
`
Short answer: you can't and still be platform independent. Most browsers just don't allow javascript to manipulate the filesystem.
That said, you might be able to get away with some very platform-specific hacks. For example, IE offers the execCommand function, which you could use to call SaveAs. If you did that within an IFrame that had the data you wanted to save, you might get it working -- but only on IE. Other options (again, I'm going Microsoft specific here) include this Silverlight hack, or ActiveX controls.
I think for full platform compatibility, you're just going to have to suck it up and provide a server-side download option.
[Edit]
Whoops! I didn't do enough due diligence when I went link-hunting. It turns out the Silverlight hack I linked to has a server-side component. Looks like you're pretty SOL.
[Edit2]
I found a nice summary of browser compatibility for execCommand here. Although it lists question marks for the "saveas" command, maybe that might be a good route for you after all. Worth a try, perhaps?
[Edit3]
Well, I decided to do a proof of concept of the approach I suggested, and I got something fairly simple working in IE. Unfortunately, I proved in the process that this approach will not work for Firefox and doesn't appear to work in Chrome/Safari, either. So it's very platform dependent. But it works! Here's a complete working page:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<title>Javascript File Saver</title>
<script type="text/javascript">
function PageLoad() {
var fdoc = window.frames["Frame"].document;
fdoc.body.appendChild(fdoc.createTextNode("foo,bar,baz"));
}
function Save() {
var fdoc = window.frames["Frame"].document;
fdoc.execCommand("SaveAs", true);
}
</script>
</head>
<body onload="PageLoad();">
<h2>Javascript File Saver</h2>
<iframe id="Frame" style="width: 400px;">Noframe</iframe><br />
<button onclick="Save();">Save</button>
</body>
</html>
Yeah, I'm afraid you have to pass it back to the server. Make a generic "echo" script that spits out whatever parameters are fed to it.
At least you can force a download with the right MIME type:
"content-disposition","attachment; filename=data.xml"
You might want to check this out: it's called Downloadify. It uses a mix of Javascript and Flash, and can save a string in pretty much any format. Try out the demo and see for yourself!
Check out http://regany.com/blog/2014/05/30/convert-a-string-to-a-download-file-in-javascript/
Enable popups and use the following code:
var str = "the string you wan't to download";
window.open('data:text/plain,' + encodeURIComponent(str));
Probably it would be usefull (JSP variant):
private void printSaveStringButton(String fileName, String content) throws Exception {
//add new invisible container with write / save functions
out.println("<iframe id=\"xmlContentId\" style=\"display:none;\"></iframe>");
//save string in js variable
String jScript = "\n" +
"var SaveHelper = {\n" +
" content : null,\n" +
" saveContent : function(filename, text) {\n" +
" text=(SaveHelper.content!=null)?SaveHelper.content:text;\n" +
" var doc = document.getElementById('xmlContentId').contentWindow.document;\n" +
" doc.write(text);\n" +
" doc.execCommand(\"saveAs\",true,filename);\n" +
" doc.close();\n" +
" }\n" +
"};\n" +
"SaveHelper.content = '" + org.apache.commons.lang.StringEscapeUtils.escapeJavaScript(content) + "';\n";
out.println("<script type=\"text/javascript\">" + jScript + "</script>");
//add button that writes content into iframe container and show save dialog.
out.println("<button type=\"button\" onclick=\"SaveHelper.saveContent('"+fileName+"' )\">Save as...</button>");
}
You could probably use the parseKml function to parse the kml data in the javascript variable rather than trying to store it in a file and modifying it from javascript (which I dont think is possible due to security reasons)
https://developers.google.com/earth/documentation/kml
Frankly, I don't think this is possible. It was never intended that this could be done in javascript.

Categories