Is there a way to detect if NaCl is available on the current browser?
It seems that checking for chrome.app.isInstalled turns into false positive on some non-Chrome browsers
You can check if the browser handles the NaCl mime type. E.g.:
navigator.mimeTypes['application/x-nacl'] !== undefined.
Similarly, for PNaCl, you can check for 'application/x-pnacl'.
You can check for Chrome and a particular version of Chrome like this:
var have_nacl = false;
var have_pnacl = false;
var index = navigator.userAgent.indexOf('Chrome');
if (index != -1) {
var version = parseFloat(navigator.userAgent.substring(index + 7));
if (31 <= version) have_pnacl = true;
if (14 <= version) have_nacl = true;
}
However, this does not tell the full story. Versions 31+ have PNaCl and it's enabled by default. NaCl is only enabled by default for apps in the Chrome store so you would still need to test if NaCl is enabled. One way to do this is to set a watchdog timer then try to load an NaCl module and capture the load event. In the load event clear the watchdog timer. For example:
var watchdog;
var watchdog_time;
function watchdog_timeout() {
alert('NaCl module failed to load');
}
function watchdog_clear() {
clearTimeout(watchdog);
}
function watchdog_set(time) {
watchdog_time = time;
watchdog = setTimeout(watchdog_timeout, time);
}
watchdog_set(5000); // Timeout in 5 sec
var module = document.getElementById('module'); // Use your module's ID
module.addEventListener('load', function () {
watchdog_clear();
alert('NaCl module loaded');
}, true);
// Inject the module, where module.nmf is your NMF file.
module.innerHTML = '<embed src="module.nmf" type="application/x-nacl"/>';
This requires that you have something like the following somewhere in your HTML:
<div id="module"></div>
If your module takes awhile to download you might also want to capture the loadstart and progress events and extend the watchdog time.
function watchdog_extend() {
watchdog_clear();
watchdog_set(watchdog_time);
}
module.addEventListener('loadstart', watchdog_extend, true);
module.addEventListener('progress', watchdog_extend, true);
Related
Facing issue to open Macro document in Modern Browser(FF, chrome) and Export As Fixed Format.The below code user open macro document and set value as per the condition, next export it as fixed format.
function launch_alwaysprint (loc)
var i;
{
var w= new ActiveXObject("Word.Application");
w.Visible = true;
w.WindowState = 2; //Minimize
w.WindowState = 1; //Maximize
var obj= w.documents.open(loc);
for (i=1; i<=obj.FormFields.count; i++) {
if (obj.FormFields(i).name == "AccountOwner") {
if (document.forms[0].AccountOwnerOverride.value != "") {
obj.FormFields(obj.FormFields(i).name).Range.Fields(1).result.text = document.forms[0].AccountOwnerOverride.value;
}
else {
obj.FormFields(obj.FormFields(i).name).Range.Fields(1).result.text = document.forms[0][obj.FormFields(i).name].value;
}
}
} //End For
obj.RunAutoMacro(2);
//obj.Protect(1,true,"Xz123Asdf34");
var shell = new ActiveXObject("WScript.Shell");
var pathToMyDocuments = shell.SpecialFolders('MyDocuments')+"\\test1.pdf";
alert("Contract will be opened as a PDF but it will not be automatically saved");
obj.ExportAsFixedFormat(pathToMyDocuments,"17","true");
obj.Close(0)
w.Quit(0)
} // End Main fnc
You can't do this in a web browser.
Launching and interacting with applications on the user's computer is a security risk, and web pages are no longer allowed to do it. (This code would only have ever worked on Internet Explorer, and even then, only on certain older versions with nonstandard security zone settings.)
You will need to find another way of doing this -- probably by processing the document and generating a PDF on the server.
I have developed an add-on to communicate with a smart card. I have used winscard.dll and its functions (such as Establishment, Connecting, Transmitting).
//less-privileged scope like jsp
var element = document.createElement("MyExt1");
document.documentElement.appendChild(element);
var evt = document.createEvent("Events");
evt.initEvent("SCardConnect", true,false);
element.dispatchEvent(evt);
var CardHandle = element.getAttribute("CardHandle");
alert(CardHandle);
and
//privileged scope which exist in my add-on
.
.
.
var MyExtension1 = {
Connect : function(evt){
...
evt.target.setAttribute("CardHandle", CH.toString());
var doc = evt.target.ownerDocument;
var AnswerEvt = doc.createElement("SCardConnect");
doc.documentElement.appendChild(AnswerEvt);
var event = doc.createEvent("HTMLEvents");
event.initEvent("ConnectEvent",true,false);
AnswerEvt.dispatchEvent(event);
}
}
.
.
.
document.addEventListener("SCardConnect", function(e){myExtension1.Connect(e);}, false, true);
After a small introduction, this is my problem:
When I install the add-on in Firefox and debug the code step by step through F10 it works fine, however if I want to run the external script without interruption (without debugging), it returns null when I get attributes.
This is an event-based approach to call an add-on function from an external script function. There is another approach that used export function which I get following problem:
https://stackoverflow.com/questions/32450103/calling-a-firefox-add-on-function-from-an-external-javascript-file
You might want to move 'var CardHandle = element.getAttribute("CardHandle");' into a new function and check if its value has been valid or not in specified intervals.
var varTimer = setInterval(function(){ myTimer() }, 1000);
function myTimer() {
var CardHandle = element.getAttribute("CardHandle");
if(CardHandle is valid) stopTimer();
}
function stopTimer() {
clearInterval(varTimer);
}
I'm using osx 10.9.2, protractor 0.21.0, selenium-server-standalone 2.40.0 and chromedriver 2.9.
I'm having some problems, which (I believe) was due to window focusing issue.
When I run my e2e test using protractor, the browser window would show but my terminal will still be the one in focus. This is apparent from "Terminal" was still shown in my menu bar rather than "Chrome" (osx behavior that indicates which app is in focus).
I tried to remedy the situation by doing this to no avail:
browser.driver.getAllWindowHandles().then(function(handles) {
console.log(handles[0]);
browser.driver.switchTo().window(handles[0]);
});
This situation causes some of my tests to fail. For example, tests that include clicking a field with bootstrap datepicker won't show the calendar and making my test cannot interact with the datepicker calendar.
The situation is even worse on firefox. Firefox won't even show any dropdown menu when clicked if the browser is not in focus.
Funnily, when I click the browser window manually after it shows up the first time, the tests will work normally.
When I tried a different approach: Doing the test on a freshly installed debian linux, still not working. Behavior is similar as described above.
These are my configuration files: https://gist.github.com/giosakti/ca24a13705d15f4374b0
Unfortunately IE & Firefox don't ensure the windows handlers order, so we need iterate them. And getting focus on the new browser window/tab can be tricky too.
I've run into these issues so i created:
A helper function to overcome those issues
// Needs an element to make sure we are on the correct popup
var waitForPopUpHandle = function(elm, errorMessage) {
if (errorMessage == null) {
errorMessage = 'Expected a new browser tab or window to pop up';
};
if (elm == null) {
throw 'waitForPopUpHandle needs an element to wait for!';
};
browser.ignoreSynchronization = true; // not a protractor page
// IE & Firefox don't ensure the windows handlers order, so we need iterate them.
// First wait to have more that 1 browser tab
browser.manage().timeouts().implicitlyWait(300); // a reasonable wait-retry time
var i = 0;
var popUpHandle = browser.driver.wait(function() {
return browser.getAllWindowHandles().then(function(handles) {
if (handles.length > 1) {
return browser.switchTo().window(handles[i]).then(function() {
return browser.driver.isElementPresent(elm).then(function(result) {
if (result) {
return handles[i];
} else {
browser.sleep(400); // give it a break
i = i + 1;
if (i >= handles.length) {
i = 0;
};
return false;
};
});
});
} else {
browser.sleep(400); // give it a break
return false;
};
});
}, browser.params.timeouts.pageLoadTimeout, errorMessage);
// restore implicit wait
browser.manage().timeouts().implicitlyWait(0); //restore
return popUpHandle;
};
Sample usage of that helper
var popUpHandle = waitForPopUpHandle(by.css('div.some-element-unique-to-that-popup'));
browser.switchTo().window(popUpHandle).then(function() {
browser.ignoreSynchronization = true; // not an angular page
browser.driver.findElement(by.css('div.some-element-unique-to-that-popup')); // wait for the elm
// your expect()'s go here ...
// ...
browser.close().then(function() {
// This close() promise is necessary on IE and probably on Firefox too
var mainTab = waitForMainWindow();
expect(browser.switchTo().window(mainTab).then(function() {
browser.ignoreSynchronization = false; // restore if main window is an angular page
// Ensure we are back on the main window
// ....
return true;
})).toBe(true);
});
});
And finally waitForMainWindow helper
var waitForMainWindow = function(errorMessage) {
if (errorMessage == null) {
errorMessage = 'Expected main browser window to be available';
};
browser.ignoreSynchronization = true; // not an angular page
return browser.driver.wait(function() {
return browser.getAllWindowHandles().then(function(handles) {
if (handles.length > 1) {
var hnd = handles[handles.length - 1];
return browser.switchTo().window(hnd).then(function() {
return browser.close().then(function() {
browser.sleep(400); // wait for close
return false;
});
});
} else {
return handles[0];
};
});
}, 5000, errorMessage);
};
I found a silver lining! I downgrade the chrome using installer from http://google-chrome.en.uptodown.com/mac/old and the focus issues are gone.. (the issues still persist on firefox though)..
If you search "chrome 34 focus issues" on google, you will find several reports that maybe correlate with this issue. for example: https://productforums.google.com/forum/#!topic/chrome/pN5pYf2kolc
but I still don't know whether this was a bug or expected behavior of chrome 34. So for now I block google updater and use Chrome 33.
I know about Adobe's Flash Detection kit - but is there any way to find out simply if Flash is installed/supported by the visitor? If the browser supports Flash, that's great, but I don't care what version. I'm struggling to find a simple bit of JavaScript that would do the trick. Has anyone seen something like this?
Cheers!
http://code.google.com/p/swfobject/
JavaScript Flash Detection Library (Flash Detect)
"A (pure) JavaScript library designed to simplify the process of detecting if
the Adobe Flash Player is installed in a Web Browser."
<script language="JavaScript">
function detectPlugin() {
// allow for multiple checks in a single pass
var daPlugins = detectPlugin.arguments;
// consider pluginFound to be false until proven true
var pluginFound = false;
// if plugins array is there and not fake
if (navigator.plugins && navigator.plugins.length > 0) {
var pluginsArrayLength = navigator.plugins.length;
// for each plugin...
for (pluginsArrayCounter=0; pluginsArrayCounter < pluginsArrayLength; pluginsArrayCounter++ ) {
// loop through all desired names and check each against the current plugin name
var numFound = 0;
for(namesCounter=0; namesCounter < daPlugins.length; namesCounter++) {
// if desired plugin name is found in either plugin name or description
if( (navigator.plugins[pluginsArrayCounter].name.indexOf(daPlugins[namesCounter]) >= 0) ||
(navigator.plugins[pluginsArrayCounter].description.indexOf(daPlugins[namesCounter]) >= 0) ) {
// this name was found
numFound++;
}
}
// now that we have checked all the required names against this one plugin,
// if the number we found matches the total number provided then we were successful
if(numFound == daPlugins.length) {
pluginFound = true;
// if we've found the plugin, we can stop looking through at the rest of the plugins
break;
}
}
}
return pluginFound;
} // detectPlugin
function detectFlash() {
pluginFound = detectPlugin('Shockwave','Flash');
// if not found, try to detect with VisualBasic
if(!pluginFound && detectableWithVB) {
pluginFound = detectActiveXControl('ShockwaveFlash.ShockwaveFlash.1');
}
// check for redirection
if (pluginFound) {
alert ("You has teh flash");
}
}
detectFlash();
</script>
Adapted from:
http://developer.apple.com/internet/webcontent/detectplugins.html
Thanks to everyone in advance -
I need to load a preference before any windows are loaded at startup. Below is some /component code I have been working with. The SetPreference method seems to fail when it is called (nothing executes afterwords either) - I am assuming because the resources that it needs are not available at the time of execution...or I am doing something wrong. Any suggestions with this code or another approach to setting a preference at startup?
Thanks again,
Sam
For some reason the code formatting for SO is not working properly - here is a link to the code as well - http://samingrassia.com/_FILES/startup.js
Components.utils.import('resource://gre/modules/XPCOMUtils.jsm');
const Cc = Components.classes;
const Ci = Components.interfaces;
const ObserverService = Cc['#mozilla.org/observer-service;1'].getService(Ci.nsIObserverService);
function MyStartupService() {};
MyStartupService.prototype = {
observe : function(aSubject, aTopic, aData) {
switch (aTopic) {
case 'xpcom-startup':
this.SetPreference("my.extension.is_running", "false");
break;
case 'app-startup':
this.SetPreference("my.extension.is_running", "false");
ObserverService.addObserver(this, 'final-ui-startup', false);
break;
case 'final-ui-startup':
//make sure is_running is set to false
this.SetPreference("my.extension.is_running", "false");
ObserverService.removeObserver(this, 'final-ui-startup');
const WindowWatcher = Cc['#mozilla.org/embedcomp/window-watcher;1'].getService(Ci.nsIWindowWatcher);
WindowWatcher.registerNotification(this);
break;
case 'domwindowopened':
this.initWindow(aSubject);
break;
}
},
SetPreference : function(Token, Value) {
var prefs = Components.classes["#mozilla.org/preferences-service;1"].getService(Components.interfaces.nsIPrefService);
var str = Components.classes["#mozilla.org/supports-string;1"].createInstance(Components.interfaces.nsISupportsString);
str.data = Value;
prefs.setComplexValue(Token, Components.interfaces.nsISupportsString, str);
//save preferences
var prefService = Components.classes["#mozilla.org/preferences-service;1"].getService(Components.interfaces.nsIPrefService);
prefService.savePrefFile(null);
},
initWindow : function(aWindow) {
if (aWindow != '[object ChromeWindow]') return;
aWindow.addEventListener('load', function() {
aWindow.removeEventListener('load', arguments.callee, false);
aWindow.document.title = 'domwindowopened!';
// for browser windows
var root = aWindow.document.documentElement;
root.setAttribute('title', aWindow.document.title);
root.setAttribute('titlemodifier', aWindow.document.title);
}, false);
},
classDescription : 'My Startup Service',
contractID : '#mystartupservice.com/startup;1',
classID : Components.ID('{770825e7-b39c-4654-94bc-008e5d6d57b7}'),
QueryInterface : XPCOMUtils.generateQI([Ci.nsIObserver]),
_xpcom_categories : [{ category : 'app-startup', service : true }]
};
function NSGetModule(aCompMgr, aFileSpec) {
return XPCOMUtils.generateModule([MyStartupService]);
}
To answer your real question, which is
I have code that loads on every window load and I need to make sure that only gets executed once every time firefox starts up.
..you should just use a module, in the load handler that you wish to execute once, check a flag on the object exported from (i.e. "living in") the module, then after running the code you need, set the flag.
Since the module is shared across all windows, the flag will remain set until you close Firefox.
As for your intermediate problem, I'd suggest wrapping the code inside observe() in a try { ... } catch(e) {dump(e)} (you'll need to set a pref and run Firefox in a special way in order to see the output) and check the error returned.
I guess xpcom-startup and app-startup is too early to mess with preferences (I think you need a profile for that), note that you don't register to get xpcom-startup notification anyway. You probably want to register for profile-after-change instead.