Running Exe in Firefox why do I get an error - javascript

I run this in Firefox, when clicking on link, Firefox says NS_ERROR_FILE_UNRECOGNIZED_PATH wheread I followed the instruction from here How to open .EXE with Javascript/XPCOM as Windows "Run..."?
<html>
<head>
<script>
function RunExe(path) {
try {
var ua = navigator.userAgent.toLowerCase();
if (ua.indexOf("msie") != -1) {
MyObject = new ActiveXObject("WScript.Shell")
MyObject.Run(path);
} else {
netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
var exe = window.Components.classes['#mozilla.org/file/local;1'].createInstance(Components.interfaces.nsILocalFile);
exe.initWithPath(path);
var run = window.Components.classes['#mozilla.org/process/util;1'].createInstance(Components.interfaces.nsIProcess);
run.init(exe);
var parameters = [""];
run.run(false, parameters, parameters.length);
}
} catch (ex) {
alert(ex.toString());
}
}
</script>
</head>
<body>
Open Word
</body>

In javascript literals, a backslash indicates the beginning of an escape sequence. If you actually want to represent a backslash, you can escape it with a double backslash.
ie
'C:\\Windows\\System32\\cmd.exe /c start winword.exe'
http://www.javascriptkit.com/jsref/escapesequence.shtml
EDIT:
From the comments on the correct answer from the post you linked, it looks like the way he got it working was:
only pass the path to runexe:
javascript:RunExe('C:\Windows\System32\cmd.exe')
set the params equal to the command args:
var parameters = ["/c start winword.exe"];
So this would work theoretically:
<html>
<head>
<script>
function RunExe(path) {
try {
var ua = navigator.userAgent.toLowerCase();
if (ua.indexOf("msie") != -1) {
MyObject = new ActiveXObject("WScript.Shell")
MyObject.Run(path);
} else {
netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
var exe = window.Components.classes['#mozilla.org/file/local;1'].createInstance(Components.interfaces.nsILocalFile);
exe.initWithPath(path);
var run = window.Components.classes['#mozilla.org/process/util;1'].createInstance(Components.interfaces.nsIProcess);
run.init(exe);
var parameters = ["/c start winword.exe"];
run.run(false, parameters, parameters.length);
}
} catch (ex) {
alert(ex.toString());
}
}
</script>
</head>
<body>
Open Word
</body>
Although clearly it would be better to pass in the params as an argument than hardcode them as I've done here (or pass them in as part of the path and parse them out)

Related

.split + regex not working in web browser

In visual studio code, this runs fine.
What is supposed to happen:
1. Load text file
2. Split it into paragraphs and save them to an array
3. Lastly it should log that array.
What happens:
1. It loads text file
2. It doesn't split it by paragraphs.
3. It logs the array of a single value to the console.
As you can see with my experiments, I've tried splitting by a space (which it does fine) but for some reason, splitting by paragraph is giving it trouble.
Is there something I need to include to get regex to work? This is on Google Chrome fwiw.
const readTxt = (file) => {
var rawFile = new XMLHttpRequest();
rawFile.open("GET", file, false);
rawFile.onreadystatechange = function() {
if (rawFile.readyState === 4) {
if (rawFile.status === 200 || rawFile.status == 0) {
console.log('Book Loaded - Success!')
var allText = rawFile.responseText;
book = JSON.stringify(allText);
sentenceCollectionRaw = book.split(/(?:\r\n){2,}/);
//sentenceCollectionRaw = book.split(' ');
//sentenceCollectionRaw = book;
console.log('Book split - Success!')
console.log(sentenceCollectionRaw);
}
}
}
rawFile.send(null);
}
<html>
<head>
<title>X</title>
<script language="javascript" src="CommaRemove.js" type="text/javascript"></script>
</head>
<body>
<h1>Read Text</h1>
<body onload="readTxt('http://www.gutenberg.org/files/120/120-0.txt');">
</body>
</html>
Solved!
It just didn't like this format: (/(?:\r\n){2,}/)
But... for some reason is fine with ("\n")
I'm curious if anyone knows why?

JavaScriptCore get API console.log messages

I have a simple web app that prints streaming data to the console.log. This works just fine in a web page.
I would like to print the log messages directly onto the Xcode console as they come across the stream without using a web view.
Prefer everything to be in Swift if possible but Objective-C solution is ok.
<!DOCTYPE html>
<html lang="en">
<head>
<title>Barchart Market Data API Example</title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<script src="../dist/barchart-marketdata-api-1.0.js"></script>
<script type="text/javascript">
$(function() {
var onMarketUpdate = function(message) {
if (message.type == "TRADE") {
var q = client.getMarketState().getQuote(message.symbol);
if (q)
console.log('Symbol: ' + q.symbol +
'\nLast:' + q.lastPrice +
'\nVolume:' + q.volume +
'\nTime:' + q.time);
}
};
var client = new Barchart.RealtimeData.Connection();
client.connect('qsws-us-e-01.aws.barchart.com', 'user', 'password');
client.on('marketUpdate', onMarketUpdate, 'ESZ6');
});
</script>
<body>
</body>
</html>
I have been able to load the script above (everything in the script text/javascript tag into a file called myLib.js) as well as the required libraries
let fileLocation1 = NSBundle.mainBundle().pathForResource("jquery", ofType: "js")!
let jsSource1 : String
do {
jsSource1 = try String(contentsOfFile: fileLocation1)
} catch {
jsSource1 = "Contents of JavaScript not loaded."
}
let fileLocation2 = NSBundle.mainBundle().pathForResource("barchart-marketdata-api", ofType: "js")!
let jsSource2 : String
do {
jsSource2 = try String(contentsOfFile: fileLocation2)
} catch {
jsSource2 = "Contents of JavaScript not loaded."
}
let fileLocation3 = NSBundle.mainBundle().pathForResource("myLib", ofType: "js")!
let jsSource3 : String
do {
jsSource3 = try String(contentsOfFile: fileLocation3)
} catch {
jsSource3 = "Contents of JavaScript not loaded."
}
let context = JSContext()
context.evaluateScript(jsSource1)
context.evaluateScript(jsSource2)
context.evaluateScript(jsSource3)
I am not sure how to get the output from the console.log into the context as it is inside a Jquery anonymous function.
It really does not have to come from the console.log, I could just return the string to the mac/iOS app.

How to dynamically load an iFrame source and autofill input forms with Javascript

I need to retrieve URL parameters (which I can do successfully) and based on one parameter, decide which iframe src to fill, then with other parameters auto fill the form that is created via the form src. First issue is that I can't keep the page from going into an infinite loop. It loads properly and shows the right iframe, but the infinite loop (load) needs to stop. Second, I can't get the other parameters to autofill the input values.
Here is the code. I hope you can help. Here is the code
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/2000/REC- xhtml1-200000126/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<!-- Keep your jQuery up to date -->
<script type="text/javascript">
var urlParams;
(window.onpopstate = function () {
var match,
pl = /\+/g, // Regex for replacing addition symbol with a space
search = /([^&=]+)=?([^&]*)/g,
decode = function (s) { return decodeURIComponent(s.replace(pl, " ")); },
query = window.location.search.substring(1);
urlParams = {};
while (match = search.exec(query))
urlParams[decode(match[1])] = decode(match[2]);
})();
var test = urlParams["entry"];
var test2 = urlParams["test"];
function iframedirect(){
if (test=="sldk") {
document.getElementById("frame1").src = "http://na-sj09.marketo.com/lp/cochlearsandbox/UpgradeInterest_IFrameLandingPage.html";
var f1 = frames['frame1'].document.forms['mktForm_1108'];
f1.elements['FirstName'].value = test;
}else{
document.getElementById("frame1").src = "http://na-sj09.marketo.com/lp/cochlearsandbox/CAM-UpgradeInterestForm_iFrameLandingPage2ndOption.html";
}
}
</script>
</head>
<body id="bodyId" class="mktEditable" align="center" >
<iframe id="frame1" src="" onload="iframedirect()" height="750px" width="620px" scrolling="no" frameborder="0" marginwidth="0"></iframe>
</body>
</html>
The infinite loop is probably caused by the result of the function iframedirect().It changes the src of the iframe and triggers the onload event again and again.
You could use a variable to point out if the iframe has been loaded by iframedirect().
var test = urlParams["entry"];
var test2 = urlParams["test"];
var isLoadedByIFrameDirect = false;
function iframedirect() {
if(!isLoadedByIFrameDirect) {
if (test=="sldk") {
document.getElementById("frame1").src = "url1";
var f1 = frames['frame1'].document.forms['mktForm_1108'];
f1.elements['FirstName'].value = test;
}else{
document.getElementById("frame1").src = "url2";
}
isLoadedByIFrameDirect = true;
}
}
Okay, so the problem is that I created a sel-freferencing onload event. Bad idea. To solve the issue, I needed to remove the onload from the iframe element. I tried putting it in the Body before without luck. But I might have screwed it up, so don't ignore that option if you have a similar situation. I decided to do it with Javascript right after the function. If you are a novice, the difference between Javascript onload and HTML onload can be found here
W3Schools onload Event
I still have not solved the "autofilling iframe form from url parameter" portion of this problem. I will make an additional comment to this answer once I figure that out.
In any case, here is the code
function iframedirect() {
if(!isLoadedByIFrameDirect) {
if (test=="sldk") {
document.getElementById("frame1").src = "http://na- sj09.marketo.com/lp/cochlearsandbox/UpgradeInterest_IFrameLandingPage.html";
var f1 = frames['frame1'].document.forms['mktForm_1108'];
f1.elements['FirstName'].value = test;
}else{
document.getElementById("frame1").src = "http://na-sj09.marketo.com/lp/cochlearsandbox/CAM-UpgradeInterestForm_iFrameLandingPage2ndOption.html";
}
isLoadedByIFrameDirect = true;
}
}
window.onload = iframedirect;

Node.js -- Robust HTML parsing + access to javascript functions in HTML

I'm new to node, and looking to extract javascript info from the following example page:
contrived.html:
<html>
<head>
<title>
This is a contrived example
</title>
<script type="text/javascript">
var filenames = new Array()
filenames[filenames.length] = "http://domainwhatever.s3.amazonaws.com/780BONNYVILLECOLDLAKECHRYSLER/4431716.jpg";
filenames[filenames.length] = "http://domainwhatever.s3.amazonaws.com/780BONNYVILLECOLDLAKECHRYSLER/4431716_1.jpg";
filenames[filenames.length] = "http://domainwhatever.s3.amazonaws.com/780BONNYVILLECOLDLAKECHRYSLER/4431716_2.jpg";
filenames[filenames.length] = "http://domainwhatever.s3.amazonaws.com/780BONNYVILLECOLDLAKECHRYSLER/4431716_3.jpg";
filenames[filenames.length] = "http://domainwhatever.s3.amazonaws.com/780BONNYVILLECOLDLAKECHRYSLER/4431716_4.jpg";
function pixplosion_Content()
{
var eElement = document.getElementById('idLoading');
if( eElement ) eElement.style.display = 'none';
return "<pixplosion test=\"test\" flashGasket=\"http://www.realelivepeople.com/pixplosion/assets/flashGasket.swf?contentPath=\" ytBridge=\"/images/image.php?pixplosion=ytbridge\"><tab test=\"test\" label=\"Photos (%1)\" icon=\"Image\" autoIterate=\"false\" ><tab test=\"test\" label=\"Vehicle Photos (%1)\" icon=\"\" autoIterate=\"true\" startFocused=\"true\" >
<image>http://s3.domainwhatever_2.com/vehicles/photos/3726/1300025.jpg</image>
<image>http://s3.domainwhatever_2.com/vehicles/photos/3726/1300025/35102537.jpg</image>
<image>http://s3.domainwhatever_2.com/vehicles/photos/3726/1300025/35102538.jpg</image>
<image>http://s3.domainwhatever_2.com/vehicles/photos/3726/1300025/35102539.jpg</image>
<image>http://s3.domainwhatever_2.com/vehicles/photos/3726/1300025/35102540.jpg</image>
<image>http://s3.domainwhatever_2.com/vehicles/photos/3726/1300025/35102541.jpg</image>
<image>http://s3.domainwhatever_2.com/vehicles/photos/3726/1300025/35102542.jpg</image>
<image>http://s3.domainwhatever_2.com/vehicles/photos/3726/1300025/35102543.jpg</image><image>http://s3.domainwhatever_2.com/vehicles/photos/3726/1300025/35102544.jpg</image><image>http://s3.domainwhatever_2.com/vehicles/photos/3726/1300025/35102545.jpg</image><image>http://s3.domainwhatever_2.com/vehicles/photos/3726/1300025/35102546.jpg</image></tab></tab></pixplosion>";
}
</script>
</head>
<body>
</body>
</html>
Jsdom chokes on this HTML using its default parser, so I've used aredridel/html5 parser from github. It seems to work for reading in HTML, through jQuery, but I don't have access to function definitions like I did with jsdom and its default parser.
For example, the following:
console.log(window.filenames);
With the default parser gives me an array.
With the HTML5 parser, it gives me:
undefined
Here is my code:
var jsdom = require("jsdom"),
fs = require('fs'),
HTML5 = require('html5');
fs.readFile('contrived.html', 'utf-8', function(err, data) {
if (err) {
throw err;
}
var document = jsdom.jsdom(data, null, {parser: HTML5});
// HTML data should be in document creation call
var script = document.createElement("script");
// HTML data SHOULD NOT be in window creation call
var window = document.createWindow();
var parser = new HTML5.Parser({document: window.document});
parser.parse(data);
script.src = 'http://code.jquery.com/jquery-1.4.2.js';
script.onload = function(window) {
console.log('this is a test');
console.log(window.filenames);
console.log(window.pixplosion_Content);
}
document.head.appendChild(script);
});
Am I missing something, or is this functionality just not available?
Many thanks.

"Read" XML with Javascript

Still playing with Chrome Extension and have a little problem when I want to get some information from an XML file. Here is how the XML look :
<?xml version='1.0' encoding='utf8'?>
<objects>
<url>
<domain>...</domain>
<nb_clics>...</nb_clics>
<alias>...</alias>
<title>...</title>
<source>...</source>
<description />
</url>
</objects>
I've tried this but, no result :
<html>
<head>
<style>
body {
width:160px;
}
p {
font-weight:bold;
margin-bottom:0;
}
</style>
</head>
<script type="text/javascript">
function DOMImplementation(sUrl, fCallback) {
var dom;
if(window.ActiveXObject) {
dom = new ActiveXObject("Microsoft.XMLDOM");
dom.onreadystatechange = function() {
if(dom.readyState == 4) {
fCallback(dom);
}
};
}
else if(document.implementation && document.implementation.createDocument) {
dom = document.implementation.createDocument("", "", null);
dom.onload = function() {
fCallback(dom);
}
}
else {
alert("ERROR");
return;
}
dom.load(sUrl);
}
function shrimit() {
var nicknick = localStorage["nick_name"];
var apiapi = localStorage["api_key"];
var yourc = document.getElementById("your");
chrome.tabs.getSelected(null,function(tab) {
var tablink = tab.url;
if(!nicknick || !apiapi){
yourc.setAttribute("value","Set the options");
} else {
DOMImplementation("post.xml", getData);
function getData(oData) {
var tablink2 = oData.getElementsByTagName("alias")[0].firstChild.data;
yourc.setAttribute("value",tablink2);
}
}
});
}
</script>
<body onload="shrimit()">
<input id="your" name="your" type="text" value="" />
</body>
</html>
Can you help me ?
Use XMLHttpRequest to load an XML file. This is standardised and reliable across browsers. document.implementation.createDocument ... load is not.
(You may get an HTMLDocument instead of a plain XML Document. Normally sniff for DOMParser before falling back to document.implementation.createDocument. Also createDocument('', '', null); is invalid: you can't have an empty-string root element name. Use createDocument(null, 'name', null). Also, finally, best not use the name DOMImplementation because that's the name of a built-in interface/class present in Chrome and some others.)
Finally, using a function statement inside an else clause is invalid in JavaScript. Browsers tend to allow it but with variable results. Either declare the function at the top level, or use an inline function expression.

Categories