javascript detect if being run in hta - javascript

We'd like to allow our users to download an hta file and run our web app inside it, and have certain pages detect that they are running in an hta file and offer additional features that a web app wouldn't normally have permission to do.
How can I simply detect if the page is being browsed from an hta file container?

window.location.protocol=='file:' would indicate a local page but that could be a local
html page or a local hta.
I'm thinking window.external may be different in each context.
So making and opening a.htm and a.hta containing:
<script>document.write(window.external)</script>
We get:
IE: [object]
FireFox: [xpconnect wrapped (nsISupports, nsISidebar, nsISidebarExternal, nsIClassInfo)]
Chrome: [object Object]
HTA: null
So, isHTA=(window.external==null) would indicate the HTA context.
Or, isHTA=false;try{isHTA=(window.external==null)}catch(e){}
To be on the safe side, since I have only tested current versions of IE, FF, and Chrome and who knows what the other browsers will do.

What about just:-
var isHTA = (document.all && top.document && (top.document.getElementsByTagName('application')[0]));

HTAs are unique in how they populate the DOM with the <HTA:APPLICATION> tag. I use the following to grab the HTA object:
var hta;
var elements = document.getElementsByTagName("APPLICATION");
for(var i=0; i<elements.length; i+=1) {
if ("hta" === elements[i].scopeName.toString().toLowerCase()) {
hta = elements[i];
break;
}
}
// To test if the page is an HTA:
var isHta = (undefined !== hta);
In other browsers, you will have to use the full tag name to access the same object:
// For Firefox/Chrome/IE
var elements = document.getElementsByTagName("HTA:APPLICATION");

I haven't tested, but wouldn't just looking at window.location work?

This might fit the bill. Verifying the attributes could be removed.
<hta:application id="myHTA"/>
<script>
alert("isHTA = " + isHTA("myHTA"));
function isHTA(htaId) {
var retval = false;
var hta = window[htaId];
if (!hta) {
// hta wasn't defined
} else if (hta.scopeName != "hta") {
// hta:application
} else if (hta.nodeName != "application") {
// hta:application
} else if (hta.tagName != "application") {
// hta:application
} else {
retval = true;
// attributes only a real hta would have
var attribKeys = [
"applicationName",
"border",
"borderStyle",
"caption",
"commandLine",
"contextMenu",
"icon",
"innerBorder",
"maximizeButton",
"minimizeButton",
"scroll",
"scrollFlat",
"selection",
"showInTaskBar",
"singleInstance",
"sysMenu",
"version",
"windowState"
];
for (var i=0;i<attribKeys.length;i++) {
var attribKey = attribKeys[i];
if (!hta.attribKey === undefined) {
retval = false;
break;
}
}
}
return retval;
}
</script>

Checking the commandLine property of the HTA-Application object is the best method to see if you are running as real HTML-Application, because this property is only available in the mshta.exe.
You need to get the HTM-Application object to check this property. If you don't know the ID of the object you can use this code:
// Check if running in a HTML-Application
var isHTA = false;
var htaApp = document.getElementsByTagName("HTA:APPLICATION")
if (!htaApp.length) {
htaApp = document.getElementsByTagName("APPLICATION");
}
if (htaApp.length == 1 && htaApp[0]) {
isHTA = typeof htaApp[0].commandLine !== "undefined";
}

guess not many people still using HTA nowadays, anyway, I think the below should cover all the scenarios:
<script language=javascript>
var VBScriptVersion = "";
function getVBScriptVersion() {
var firstScriptBlock = document.getElementsByTagName('script')[0];
var tmpScript = document.createElement('script');
tmpScript.setAttribute("language", "VBScript");
tmpScript.text = 'VBScriptVersion = ScriptEngineMajorVersion & "." & ScriptEngineMinorVersion';
tmpScript.async = false;
tmpScript.onload = function() {
this.parentNode.removeChild(this);
}
firstScriptBlock.parentNode.insertBefore(tmpScript, firstScriptBlock);
return VBScriptVersion;
}
var isHTA = (getVBScriptVersion()!="" && window.external==null);
</script>

Related

how to remember clicked href and redirect to it javascript

My home page has a couple of links: one for English version and the other for French version. Something like this:
<a class="ensite" href="/en">English</a>
<a class="ensite" href="/fr">French</a>
I want to use JavaScript to remember the last choice made by visitors and when they come again, they don't have to choose the language one more time because I want them to be autoredirected to the preferred language using cookies.
P.S. the visitors are strangers, not registered users. I want to store cookies in visitors' browsers, not in the database. Please, help me by providing me with the full solution.
Gelerally, the idea is: set handlers on links and upon clicking save preferred version into localStorage. Then every time user loads any page of your site, just check, whether the url contains the language context ("en"/"fr") the user chose before. If yes - do nothing, user opened the right version; if not - redirect him to the previously saved version. The following is a Vanilla approach (not properly tested). You will have to tweak it (attachEvent etc.) or use jQuery library to implement similar ideas in a shorter and more cross-browser way.
<a class="ensite" href="/en">English</a>
<a class="ensite" href="/fr">French</a>
JS:
function LanguageManager(selector) {
this.langLinks = document.querySelectorAll(selector);
}
LanguageManager.prototype.setHandler = function() {
var self = this;
this.langLinks.forEach(function(langLink) {
langLink.addEventListener("click", self.handler, false);
});
}
LanguageManager.prototype.redirect = function() {
var link = storageManager.restoreDataFromStorage();
if(link && !~window.location.href.indexOf(link)) window.location.href = link;
}
LanguageManager.prototype.handler = function() {
var e = event || window. event;
var elem = e.target || e.srcElement;
if(e.preventDefault) e.preventDefault(); else e.returnValue = false;
storageManager.saveDataToStorage(elem.href);
location.href = elem.href;
}
function StorageManager() {
this.storageName = "languageVersion";
this.storageData = null;
}
StorageManager.prototype.isStorageAvailable = function(type) {
try {
var storage = window[type], x = '__storage_test__';
storage.setItem(x, x);
storage.removeItem(x);
return true;
} catch(e) { return false; }
}
StorageManager.prototype.saveDataToStorage = function(data) {
if(!this.isStorageAvailable('localStorage')) {
this.storageData = data;
return false;
}
try {
localStorage.setItem(this.storageName, JSON.stringify(data));
return this.storageName;
} catch(e) {
this.storageData = data;
return false;
}
}
StorageManager.prototype.restoreDataFromStorage = function() {
if(this.storageData) return this.storageData;
return JSON.parse(localStorage.getItem(this.storageName));
}
var storageManager = new StorageManager();
var languageManager = new LanguageManager(".ensite");
languageManager.setHandler();
languageManager.redirect();
Also notice, that there may be issues depending on how you implement language contexts on your site. You can start with my code on your own and tweak it or find someone else to get this properly done.
Just tested this, it works perfect.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<a class="ensite" href="" onclick ="localStorage.setItem('language','en')">English</a>
<a class="ensite" href="" onclick = "localStorage.setItem('language','fr')">French</a>
<script>
$(document).ready(function(){
var language = (localStorage.getItem('language') == null)? 'en' : localStorage.getItem('language');
console.log(language);
})
</script>

Chrome Extension to C#?

I got the following code which was written into a Chrome Extension (Javascript?)
;
(function() {
function findCaptcha() {
return document.querySelector('.g-recaptcha') || document.getElementById('g-recaptcha');
}
function completeCaptch(intervalID) {
intervalID = setInterval(function() {
if (findCaptcha() != null) {
findCaptcha()
.remove();
clearInterval(intervalID);
}
}, 200);
}
var loadedID = null;
if (location.hash === '#checkout' || location.pathname === '/checkout') {
completeCaptch(loadedID);
}
var stateID = null;
window.addEventListener('popstate', function(event) {
stateID = null;
clearInterval(stateID);
if (location.hash === '#checkout' || location.pathname === '/checkout') {
completeCaptch(stateID);
}
}, false);
})();
Reading this code is simple enough, it calls the function completeCaptch with some sort of ID that is irrelevant and then calls the function findCaptch if it is present (return document.querySelector('.g-recaptcha') || document.getElementById('g-recaptcha');) and simply removes the document.ID by calling .remove();
This is code that bypasses reCAPTCHA in a demo and I was wondering if it is possible to convert this code (whatever it was written in) to C# if I were to use a .net WebBrowser.
Using a .net WebBrowser I would be able to getElementById but would I be able to call .remove() in C#?
Thanks.
Checkout the HtmlAgilityPack library. It's a fantastic library for dealing with HTML DOMs, allowing you to do something like this:
doc.DocumentNode.SelectSingleNode("/xpath/to/node").Remove();

Javascript not working on simple test page

I'm trying to test my local storage so I've tried a few examples.
this example worked before but now its not. not sure what happened
https://stackoverflow.com/questions/30116818/how-to-use-local-storage-form-with-html-and-javascript?noredirect=1#comment48344527_30116818/
Now I am trying this code and nothing pops up on if else, it just says local storage is
function lsTest() {
var test = 'test';
try {
localStorage.setItem(test, test);
localStorage.removeItem(test);
return true;
} catch(e) {
return false;
}
}
var elem = document.getElementById('status');
if (lsTest() === true) {
elem.innerHTML += 'available.';
} else {
elem.innerHTML += 'unavailable.';
}
html
<div id="status">Local Storage is </div>
full code
http://tny.cz/39896a73
You should open your page using a webserver and not your local file system. The browser saves the localstorage data based on the host(domain). This prevents cross site local storage access.
Try this, using a webserver as Nimrodx said.
window.onload = function(){
function lsTest(){
var test = 'test';
try {
localStorage.setItem(test, test);
localStorage.removeItem(test);
return true;
} catch(e) {
console.log(e);
return false;
}
}
var elem = document.getElementById('status');
if(lsTest() === true){
elem.innerHTML += 'available.';
}
else{
elem.innerHTML += 'unavailable.';
}
};
There is no issue with your method, but I didn't see any call to this method.
To make it functional, you need to call it with some event. Like: button / anchor onlick, window load / ready as following:
Javascript:
window.onload = function(){lsTest();}
jQuery:
jQuery(document).ready(function(){
lsTest();
});
DEMO
However, if you just want to check the browser compatibility of localStorage / sessionStorage then if(typeof(Storage) !== undefined){} is quite useful.

Here is a new type of ad javascript by change "window.opener.location", how can i block it?

One of my friend climes that his Chrome browser tab sometimes changed into "tamll.com", which was the biggest shopping website in China.
At first I think it may be caused by a malware. But he has a clean os, and he checked everything in his computer.
Then I found this javascript. The code is always in the bottom of this question. And this script is being included in "bbs.gfan.com".
The script use window.opener.location to change another browser tab's webpage. When you open any pages in "bbs.gfan.com" from google.com(for example search "bbs.gfan.com" in google and click the first answer), this script check if the window.opener is not null, and set the window.opener.location to _5had0w.mall. Then the window.opener tab will be jumped to the new address.
Is there any way to block a script when it try to change window.opener.location? Or is there a way to directly disable the window.opener.location?
I think a normal webpage will never change this variable, it may only use by a ad script like this.
This kind of ad script made me feel sick. It is not only open a ad webpage but also another webpage will gone...
if ("undefined" == typeof (_5had0w)) {
_5had0w = [];
_5had0w.ssite = new RegExp("(www.baidu.com)|(www.google.c)|(www.youdao.com)|(search.cn.yahoo.com)|(search.yahoo.com)|(114search.118114.cn)|(bing.118114.cn)|(search.114.vnet.cn)|(bing.com)|(www.soso.com)|(www.sogou.com)|(www.taobao.com)|(gougou.com)|(www.gouwo.com)|(cache.baidu.com)|(m.baidu.com)|(baidu.asp)|(hao123.com)|(265.com)|(114la.com)|(115.com)|(etao.com)", "i");
_5had0w.win = window;
try {
if (parent && parent.f && parent.document.getElementById("fulliframe")) {
_5had0w.win = parent
}
} catch (e) {}
_5had0w.getcookie = function (sName) {
var aCookie = document.cookie.split("; ");
for (var i = 0; i < aCookie.length; i++) {
var aCrumb = aCookie[i].split("=");
if (sName == aCrumb[0]) return unescape(aCrumb[1])
}
return ""
};
_5had0w.setcookie = function (sValue) {
date = new Date();
date.setMinutes(date.getMinutes() + 100);
document.cookie = "oc_busy=" + escape(sValue) + "; expires=" + date.toGMTString() + ";path=/"
};
_5had0w.mall = "http://gomallg.blogbus.com/?76";
_5had0w.np = false;
_5had0w.nvIt = function (lochref) {
try {
_5had0w.win.opener.location = lochref
} catch (e) {
try {
_5had0w.win.opener.navigate(lochref)
} catch (e2) {
try {
_5had0w.win.opener.opener.navigate(lochref)
} catch (e3) {
_5had0w.np = true
}
}
}
};
_5had0w.nvUrl = function () {
var _co = _5had0w.getcookie("oc_busy");
if (_co == "" || _co.indexOf("mall") < 0) {
_5had0w.nvIt(_5had0w.mall);
if (!_5had0w.np) {
_5had0w.setcookie(_co + "_mall")
}
}
};
_5had0w.oload = function () {
if (_5had0w.win.opener && "" == _5had0w.getcookie('rf6_auth')) {
if (_5had0w.ssite.test(_5had0w.win.document.referrer)) {
_5had0w.nvUrl()
}
}
};
try {
if (document.attachEvent) {
window.attachEvent("onload", _5had0w.oload)
} else {
window.addEventListener("load", _5had0w.oload, false)
}
} catch (e) {}
}
This web application is taking advantage of the fact that Google and other websites are being opened from gfan.com. Therefore, the gfan.com web application does have some control over the new windows, since it opened them.
If the script at the bottom of the application is what you suspect is causing the problem, you could try one of several adblockers you can get for Chrome and Firefox that are installable as extensions.
If that doesn't work, you could try to edit your host file and point the remote script's domain to 127.0.0.1 so you override the DNS locally. This assumes it is a remote script and not served from gfan.com itself; otherwise, you won't be able to access gfan.com either.
Chrome Adblock is an adblocker you can try.

" iframe.contentDocument" Not Working in IE8 and FF(3.5 and below) any other steps to solve this?

I used this "iframe.contentDocument" in js file-uploader , But it not working in IE8 ,Firefox(3.5 and below versions.
How can i solve this by using other DOM's for working with iframe ?
Thanks to all
Try
var doc;
var iframeObject = document.getElementById('iframeID'); // MUST have an ID
if (iframeObject.contentDocument) { // DOM
doc = iframeObject.contentDocument;
}
else if (iframeObject.contentWindow) { // IE win
doc = iframeObject.contentWindow.document;
}
if (doc) {
var something = doc.getElementById('someId');
}
else {
alert('Wonder what browser this is...'+navigator.userAgent);
}

Categories