Possible to run userscript in IE11 - javascript

I have a custom userscript that I'm running in Chrome and Firefox using Tampermonkey/Greasemonkey.
Is there any way of using this script in IE11? Or is there any plugins for IE11 that does what Tampermonkey/Greasemonkey does?

TrixIE WPF4.5 claims to emulate Greasemonkey on IE11.
Unfortunately, the original Trixie and IE7Pro stopped working around IE8-ish.

I use localStorage to make it work, which is supported by IE8 or later.
Steps:
Run the following code in IE's developer tool when the current window is in the domain where you want the script to run in:
var scriptName = 'Hello world';
function scriptBody(){
//---userscript starts--->
document.body.innerHTML = '<h1>Hello world!</h1>';
//---userscript ends--->
}
var script = scriptBody.toString()
.split('//---userscript starts--->')[1]
.split('//---userscript ends--->')[0];
localStorage.setItem(scriptName, script);
Create a bookmark and modify the URL into:
javascript:(function(){eval(localStorage.getItem('Hello world'));})()
Advantages:
No additional plugin needed.
Almost no script text length limit.
Disadvantages:
Need a user to click on a bookmark to run the script.
Need a reinstall if a user clears the browser cache.

A simple Google Search (I searched "greasemonkey for IE") yields various alternatives available for other browsers:
http://en.wikipedia.org/wiki/Greasemonkey#Equivalents_for_other_browsers
For Internet Explorer, similar functionality is offered by IE7Pro,[19] Sleipnir,[20] and iMacros.

Fiddler supports modifying the response of http requests.
We can use this feature to load userscript in any browser, include IE8.
This is an example:
static function OnBeforeResponse(oSession: Session) {
if (m_Hide304s && oSession.responseCode == 304) {
oSession["ui-hide"] = "true";
}
// match url
if (oSession.fullUrl == "http://apply.ccopyright.com.cn/goadatadic/getR11List.do") {
oSession.utilDecodeResponse();
var script = System.IO.File.ReadAllText("C:\\GitHub\\#selpic\\P660_printer\\Printer\\scripts\\form-save-load.js")
oSession.utilReplaceOnceInResponse("</body>", "<script>"+script+"</script></body>", true);
}
}
doc: Modifying a Request or Response

Just open Developer tools (press F12) and paste your script to Console, and then run it (Ctrl + Enter).

Related

chrome.extension undefined, Javascript doesn't work in Chrome

I have a Javascript code which checks which browser the user has, the code:
var xmlHR = new XMLHttpRequest();
if (navigator.userAgent.indexOf('Chrome') > -1) { // Chrome
alert(chrome); // alerts "[object Object]"
alert(chrome.extension); // alerts "undefined"
xmlHR.open("GET", chrome.extension.getURL(path), true);
} else {
// do stuff
}
chrome.extension is undefined.
I didn't include any Chrome related scripts to the .js , what's needed to be done to have 'extension' defined ?
The chrome.extension API (and most other chrome.* APIs relating to extensions) is only defined a chrome extensions, not for the open web. If you want to write a chrome extension, then there are a few good tutorials around https://developer.chrome.com/extensions/getstarted.
The method you mention (chrome.extension.getURL()) is used to reference an extension's resources - if you are trying to do that for a normal website, then it will depend on your configuration, but likely it would be easiest to query the server for the resource at the path.
Hope that helps. :)

I cant read my cookie out in google chrome but I can in all other browsers

I am setting a cookie to hide a cookie notice on a my website.
This works fine in all other browsers but Google Chrome(and Opera to it seems) (not even tested in IE yet)
Here is my code that reads out the cookies and makes the decision whether to run the show function or do nothing.
This function is called up on page load
checkCookie = function() {
var myCookieSet = getCookie("useofcookies");
if (myCookieSet != "closed"){
alert('cookie is not set and = '+ myCookieSet);
// run the show info bar function
init();
}else {
alert('cookie HAS BEEN set and = '+ myCookieSet);
}
};
I cannot figure out what I have done wrong.
Full js file can be found here:
Cookie Notice - Pastebin
Any clues as to why would this is happening in Chrome alone would be a great help
Have you tried clearing your cache and cookies? IE a 'clean browser'?
The code looks fine and when I use your code it seems to work for me. Even in IE 8/9

Controlling a Firefox Extension via Javascript

Is it possible, using javascript, to control an overlay firefox extension? I've extracted the contents of the extension and have identified what functions/methods I need to run, but they are not accessible within the scope of the console.
Thanks in advance for any ideas.
Yes it possible to interact with other add-ons, given the right circumstances.
My test case here will be com.googlecode.sqlitemanager.openInOwnWindow(), which is part of the SqliteManager addon.
In newer builds (I'm using Nightly), there is the Browser Toolbox. With it is is as simple as opening a toolbox and executing com.googlecode.sqlitemanager.openInOwnWindow() in the Console.
You may instead use the Browser Console (or any chrome enabled WebDev Console for that matter, e.g. the Console of "about:newtab"). But you need some boilerplate code to first find the browser window. So here is the code you can execute there: var bwin = Services.wm.getMostRecentWindow("navigator:browser"); bwin.com.googlecode.sqlitemanager.openInOwnWindow()
Again, enable chrome debugging. Then open a Scratchpad and switch to Chrome in the Environment menu. Now executing com.googlecode.sqlitemanager.openInOwnWindow() in our Scratchpad will work.
You may of course write your own overlay add-on.
As a last resort, patch the add-on itself.
Bootstrapped/SDK add-ons: you can load XPIProvider.jsm (which changed location recently) and get to the bootstrapped scope (run environment of bootstrap.js) via XPIProvider.bootstrapScopes[addonID], and take it from there (use whatever is in the bootstrap scope, e.g. the SDK loader).
Now about the right circumstances: If and how you can interact with a certain add-on depends on the add-on. Add-ons may have global symbols in their overlay and hence browser window, such as in the example I used. Or may use (to some extend) JS code modules. Or have their own custom loader stuff (e.g. AdBlock Plus has their own require()-like stuff and SDK add-ons have their own loader, which isn't exactly easy to infiltate)...
Since your question is rather unspecific, I'll leave it at this.
Edit by question asker: This is correct, however I figured I'd add an example of the code I ended up using in the end, which was in fact taken directly from mozilla's developer network website:
In my chrome js:
var myExtension = {
myListener: function(evt) {
IprPreferences.setFreshIpStatus(true); // replace with whatever you want to 'fire' in the extension
}
}
document.addEventListener("MyExtensionEvent", function(e) { myExtension.myListener(e); }, false, true);
// The last value is a Mozilla-specific value to indicate untrusted content is allowed to trigger the event.
In the web content:
var element = document.createElement("MyExtensionDataElement");
element.setAttribute("attribute1", "foobar");
element.setAttribute("attribute2", "hello world");
document.documentElement.appendChild(element);
var evt = document.createEvent("Events");
evt.initEvent("MyExtensionEvent", true, false);
element.dispatchEvent(evt);
Update for Firefox 47 and up
Things changed drastically in Firefox 47. This is the new way to access it.
var XPIScope = Cu.import('resource://gre/modules/addons/XPIProvider.jsm');
var addonid = 'Profilist#jetpack';
var scope = XPIScope.XPIProvider.activeAddons.get(addonid).bootstrapScope
Old way for < Firefox 47
Update for methods of today
Typically you will do so like this:
If i wanted to get into AdBlocks scope, I check AdBlock id, it is {d10d0bf8-f5b5-c8b4-a8b2-2b9879e08c5d} so I would go:
var XPIScope = Cu.import('resource://gre/modules/addons/XPIProvider.jsm');
var adblockScope = XPIScope.XPIProvider.bootstrapScopes['{d10d0bf8-f5b5-c8b4-a8b2-2b9879e08c5d}'];
You can now tap into anything there.
Another example, I have an addon installed with id NativeShot#jetpack
I would tap into it like this:
var XPIScope = Cu.import('resource://gre/modules/addons/XPIProvider.jsm');
var nativeshotScope = XPIScope.XPIProvider.bootstrapScopes['NativeShot#jetpack'];
if you do console.log(nativeshotScope) you will see all that is inside.

Checking if user has a certain extension installed

I just found out that the Screen Capture by Google extension makes my website's window.onresize event not fire.
I want to perform a javascript check to see if the user has ScreenCapture installed and if so, warn the user of the problem.
A year ago I think I heard of some javascript code that could do this, maybe using some google API, but I don't remember.
Any insight on this? I haven't developed any extensions so I don't really know how they work.
[EDIT]
So I have been asked to show some code. As seen in my previous question ( window.onresize not firing in Chrome but firing in Chrome Incognito ), the problem occurs on any window.onresize event function, so I don't think my code really matters.
Also, there is quite a lot of my code, I don't know how much of it to paste or if it would be helpful.
var debounce = function (func, threshold, execAsap)
{
var timeout;
return function debounced () {//alert("1.1 Y U NO WORK?");
var obj = this, args = arguments;
function delayed () {
if (!execAsap)
func.apply(obj, args);
timeout = null;
}
if (timeout)
clearTimeout(timeout);
else if (execAsap)
func.apply(obj, args);
timeout = setTimeout(delayed, threshold || 100);
};
};
window.onresize = debounce(function (e) { //alert("1.2 Y U NO WORK?");
flag = true;
var point = window.center({width:1,height:1});
doCenter(point);
// does something here, but only once after mouse cursor stops
}, 100, false);
I would like to stress that the problem is not due to the debounce. window.onresize = t; function t (e) { alert("wtf?");} won't work either.
[EDIT2]
Here's the result:
var screenCapture = null;
var screenCaptureImg = document.createElement("img");
screenCaptureImg.setAttribute("src", "chrome-extension://cpngackimfmofbokmjmljamhdncknpmg/images/arrow.png");
/*
* Add event listeners for both "load"- and "error"-event
* Set the variable showing the existence of the extension by
* setting it to "true" or "false" according to the fired event
*/
screenCaptureImg.addEventListener("load", doLoad, false);
function doLoad(e){
screenCapture = true; //removeImgTag(e);
alert("I've so cleverly detected that your Chrome has the ScreenCapture extension enabled. \n\nThis extension interferes with my website's DOM and long story short, it won't be able to scale properly.\n\nSo please disable it. \nConsider this extension: \"Disable All Extensions Plus\", it's a handy selective disabler.");
}
screenCaptureImg.addEventListener("error", function(e){
screenCapture = false; //removeImgTag(e);
}, false);
/*
function removeImgTag(e) {
e.currentTarget.parentNode.removeChild(e.currentTarget);
}
*/
Note that I couldn't get removeImgTag to work, because (at least in chrome), I don't seem to have access to the document object in order to create or remove elements from my page, from within these event functions. This is also why I'm displaying an alert instead of elegantly writing up a document.getElementById("something").innerHTML=...
To detect if an extension is installed in Chrome, you can check for a known resource included in the extension such as an image. Resources for the extension are referenced using the following URL pattern:
chrome-extension://<extensionID>/<pathToFile>
The basic detection technique involves creating a hidden image tag and attaching load and error events to it to see if the image loads (as described here for Firefox):
extensionImg.setAttribute("src", "chrome-extension://<INSERT EXTENSION ID HERE>/images/someImage.png"); // See below for discussion of how to find this
/*
* Add event listeners for both "load"- and "error"-event
* Set the variable showing the existence of the extension by
* setting it to "true" or "false" according to the fired event
*/
extensionImg.addEventListener("load", function(e) {
extensionExists = true;
removeImgTag(e);
}, false);
extensionImg.addEventListener("error", function(e) {
extensionExists = false;
removeImgTag(e);
}, false);
function removeImgTag(e) {
e.currentTarget.parentNode.removeChild(e.currentTarget);
}
Check the installation directory of the extension in the Chrome configuration to find a likely target for detection. On my Linux workstation extensions are located in:
~/.config/chromium/Default/Extensions
You can see that I have 3 extensions installed right now:
~/.config/chromium/Default/Extensions$ ls
cpecbmjeidppdiampimghndkikcmoadk nmpeeekfhbmikbdhlpjbfmnpgcbeggic
cpngackimfmofbokmjmljamhdncknpmg
The odd looking names are the unique IDs given to the extension when it is uploaded to the Chrome webstore. You can obtain the ID either from the webstore or by going to the Extensions tab (wrench -> Extensions) and hovering over the link to the extension in question, or "Screen Capture (by Google)" in this case (note the asterisked extension ID):
https://chrome.google.com/webstore/detail/**cpngackimfmofbokmjmljamhdncknpmg**
In the extension directory there will be one or more versions; you can ignore this. Within the version directory is the actual content of the extension:
~/.config/chromium/Default/Extensions/cpngackimfmofbokmjmljamhdncknpmg/5.0.3_0$ ls
account.js images page.js sina_microblog.js
ajax.js isLoad.js picasa.js site.js
background.html _locales plugin style.css
editor.js manifest.json popup.html ui.js
facebook.js notification.html sha1.js upload_ui.js
hotkey_storage.js oauth.js shortcut.js
hub.html options.html showimage.css
i18n_styles page_context.js showimage.html
In the case of the Screen Capture extension there are a number of images to use:
~/.config/chromium/Default/Extensions/cpngackimfmofbokmjmljamhdncknpmg/5.0.3_0/images$ ls
arrow.png icon_128.png icon_save.png print.png
copy.png icon_16.png line.png region.png
cross.png icon_19.png loading.gif screen.png
custom.png icon_32.png loading_icon.gif sina_icon.png
delete_account_icon.png icon_48.png mark.png toolbar_bg.png
down_arrow.png icon_close.png picasa_icon.png upload.png
facebook_icon.png icon_copy.png popup_bg.jpg whole.png
These can be referenced under this URL:
chrome-extension://cpngackimfmofbokmjmljamhdncknpmg/images/arrow.png
This technique obviously depends on the stability of the content of the extension. I recommend using an image that looks likely to remain through all versions.
As mentioned above, the same technique can be used to detect Firefox extensions. In this case the content URL looks like this:
chrome://<EXTENSION NAME>/content/<PATH TO RESOURCE>
On my Linux workstation Firefox extensions are located in:
~/.mozilla/firefox/<USER PROFILE ID>/extensions
Where <USER PROFILE ID> looks something like this: "h4aqaewq.default"
You can see that I have 2 extensions installed right now, one of which is a directory installation and the other of which is a XPI (pronounced "zippy") file:
~/.mozilla/firefox/h4aqaewq.default/extensions$ ls
{3e9a3920-1b27-11da-8cd6-0800200c9a66} staged
firebug#software.joehewitt.com.xpi
The "staged" directory is where Firefox keeps extensions that will be updated (I think). The GUID directory with the brackets is a directory-based extension installation, and the .xpi file is Firebug.
Note: XPI is going away (see the link above). It's basically a zip file that can be opened and inspected by anything that understands zip. I used Emacs.
Finding the extension ID in Firefox is a bit more involved. Go to "Tools -> Add-ons", click the Extensions tab, click the "More" link next to the extension description, then click the "reviews" link to go to the Firefox extension site and get the ID from the URL (note the asterisked extension ID):
https://addons.mozilla.org/en-US/firefox/addon/**firebug**/reviews/?src=api
There's probably an easier way to do this; suggestions welcome.
TODO: how to find a likely image in a Firefox extension.
As an extra note, in Chrome you can only communicate with an extension via the shared DOM of the page: Host page communication

Why does JavaScript only work after opening developer tools in IE once?

IE9 Bug - JavaScript only works after opening developer tools once.
Our site offers free pdf downloads to users, and it has a simple "enter password to download" function. However, it doesn't work at all in Internet Explorer.
You can see for yourself in this example.
The download pass is "makeuseof". In any other browser, it works fine. In IE, both buttons do nothing.
The most curious thing I've found is that if you open and close the developer toolbar with F12, it all suddenly starts to work.
We've tried compatibility mode and such, nothing makes a difference.
How do I make this work in Internet Explorer?
It sounds like you might have some debugging code in your javascript.
The experience you're describing is typical of code which contain console.log() or any of the other console functionality.
The console object is only activated when the Dev Toolbar is opened. Prior to that, calling the console object will result in it being reported as undefined. After the toolbar has been opened, the console will exist (even if the toolbar is subsequently closed), so your console calls will then work.
There are a few solutions to this:
The most obvious one is to go through your code removing references to console. You shouldn't be leaving stuff like that in production code anyway.
If you want to keep the console references, you could wrap them in an if() statement, or some other conditional which checks whether the console object exists before trying to call it.
HTML5 Boilerplate has a nice pre-made code for console problems fixing:
// Avoid `console` errors in browsers that lack a console.
(function() {
var method;
var noop = function () {};
var methods = [
'assert', 'clear', 'count', 'debug', 'dir', 'dirxml', 'error',
'exception', 'group', 'groupCollapsed', 'groupEnd', 'info', 'log',
'markTimeline', 'profile', 'profileEnd', 'table', 'time', 'timeEnd',
'timeStamp', 'trace', 'warn'
];
var length = methods.length;
var console = (window.console = window.console || {});
while (length--) {
method = methods[length];
// Only stub undefined methods.
if (!console[method]) {
console[method] = noop;
}
}
}());
As #plus- pointed in comments, latest version is available on their GitHub page
Here's another possible reason besides the console.log issue (at least in IE11):
When the console is not open, IE does pretty aggressive caching, so make sure that any $.ajax calls or XMLHttpRequest calls have caching set to false.
For example:
$.ajax({cache: false, ...})
When the developer console is open, caching is less aggressive. Seems to be a bug (or maybe a feature?)
This solved my problem after I made a minor change to it. I added the following in my html page in order to fix the IE9 problem:
<script type="text/javascript">
// IE9 fix
if(!window.console) {
var console = {
log : function(){},
warn : function(){},
error : function(){},
time : function(){},
timeEnd : function(){}
}
}
</script>
Besides the 'console' usage issue mentioned in accepted answer and others,there is at least another reason why sometimes pages in Internet Explorer work only with the developer tools activated.
When Developer Tools is enabled, IE doesn't really uses its HTTP cache (at least by default in IE 11) like it does in normal mode.
It means if your site or page has a caching problem (if it caches more than it should for example - that was my case), you will not see that problem in F12 mode. So if the javascript does some cached AJAX requests, they may not work as expected in normal mode, and work fine in F12 mode.
I guess this could help, adding this before any tag of javascript:
try{
console
}catch(e){
console={}; console.log = function(){};
}
If you are using AngularJS version 1.X you could use the $log service instead of using console.log directly.
Simple service for logging. Default implementation safely writes the message into the browser's console (if present).
https://docs.angularjs.org/api/ng/service/$log
So if you have something similar to
angular.module('logExample', [])
.controller('LogController', ['$scope', function($scope) {
console.log('Hello World!');
}]);
you can replace it with
angular.module('logExample', [])
.controller('LogController', ['$scope', '$log', function($scope, $log) {
$log.log('Hello World!');
}]);
Angular 2+ does not have any built-in log service.
If you are using angular and ie 9, 10 or edge use :
myModule.config(['$httpProvider', function($httpProvider) {
//initialize get if not there
if (!$httpProvider.defaults.headers.get) {
$httpProvider.defaults.headers.get = {};
}
// Answer edited to include suggestions from comments
// because previous version of code introduced browser-related errors
//disable IE ajax request caching
$httpProvider.defaults.headers.get['If-Modified-Since'] = 'Mon, 26 Jul 1997 05:00:00 GMT';
// extra
$httpProvider.defaults.headers.get['Cache-Control'] = 'no-cache';
$httpProvider.defaults.headers.get['Pragma'] = 'no-cache';
}]);
To completely disable cache.
It happened in IE 11 for me. And I was calling the jquery .load function.
So I did it the old fashion way and put something in the url to disable cacheing.
$("#divToReplaceHtml").load('#Url.Action("Action", "Controller")/' + #Model.ID + "?nocache=" + new Date().getTime());
I got yet another alternative for the solutions offered by runeks and todotresde that also avoids the pitfalls discussed in the comments to Spudley's answer:
try {
console.log(message);
} catch (e) {
}
It's a bit scruffy but on the other hand it's concise and covers all the logging methods covered in runeks' answer and it has the huge advantage that you can open the console window of IE at any time and the logs come flowing in.
We ran into this problem on IE 11 on Windows 7 and Windows 10. We discovered what exactly the problem was by turning on debugging capabilities for IE (IE > Internet Options > Advanced tab > Browsing > Uncheck Disable script debugging (Internet Explorer)). This feature is typically checked on within our environment by the domain admins.
The problem was because we were using the console.debug(...) method within our JavaScript code. The assumption made by the developer (me) was I did not want anything written if the client Developer Tools console was not explicitly open. While Chrome and Firefox seemed to agree with this strategy, IE 11 did not like it one bit. By changing all the console.debug(...) statements to console.log(...) statements, we were able to continue to log additional information in the client console and view it when it was open, but otherwise keep it hidden from the typical user.
I put the resolution and fix for my issue . Looks like AJAX request that I put inside my JavaScript was not processing because my page was having some cache problem. if your site or page has a caching problem you will not see that problem in developers/F12 mode. my cached JavaScript AJAX requests it may not work as expected and cause the execution to break which F12 has no problem at all.
So just added new parameter to make cache false.
$.ajax({
cache: false,
});
Looks like IE specifically needs this to be false so that the AJAX and javascript activity run well.

Categories

Resources