Chrisissorry
Chrisissorry

Reputation: 1514

Test if JavaScript is enabled and/or running correctly

I've taken different approaches to find out whether JS is enabled / running correctly.

Usually I just do something like this:

$('.jstest').html('JavaScript works.');

<p class='jstest'></p>

So, I can see whether I accidentally disabled JS, or I have a syntax error and JS is not running correctly without consulting firebug.

Now, this requires me to modify every single page. With Greasemonkey I thought this problem could be solved, without interfering with the site. But so far I couldn't find a way. I've tried:

Both ways still work, even if the JS on the site is not executed because of script / syntax errors.

Now, I've tried to insert a noscript container with Greasemonkey and disable js to find out whether the JS on the site reacts while Greasemonkey is not affected. No, GM does not work without JS :P

It seems like GM is running independently from all other scripts on that site. Anybody know a solution?

Upvotes: 1

Views: 4814

Answers (1)

Brock Adams
Brock Adams

Reputation: 93443

Greasemonkey will run, even if the target page has JS disabled, because GM runs in its own, privileged sandbox.

You can test if JS is available on the target page by injecting a JS function and then using GM to see if that function actually ran.

Here's a script that does that:

// ==UserScript==
// @name            _JS active test
// @include         http://stackoverflow.com/questions/*
// @include         http://www.nextdaypets.com/*
// ==/UserScript==

if (window.top != window.self)  //-- Don't run on frames or iframes (normally).
    return;

//--- This function will be injected to see if JS is active on the target page.
function TestPagesJS () {
    var testNode        = document.createElement ("span");
    testNode.setAttribute ("style", "display: none;");
    testNode.setAttribute ('id',    'SpecialNodeToTestIfPageJS_IsActive');
    document.body.appendChild (testNode);
}

//--- Inject the test JS and try to run it.
var scriptNode          = document.createElement ("script");
scriptNode.textContent  = TestPagesJS.toString () + '\nTestPagesJS ();';
document.body.appendChild (scriptNode);

/*--- Do not call this function from within a timer.  If you do, and the page's JS
    is disabled (NoScript, etc.), the alerts will not fire.
*/
function CheckIsNodePresent () {
    var testNode        = document.getElementById ("SpecialNodeToTestIfPageJS_IsActive");
    if (testNode)
        alert ('Javascript works fine on the target page.');
    else
        alert ('Oops! Javascript is off or broken on the target page.');
}

CheckIsNodePresent ();



Note that the two @include directives are for a site where I allow and disallow JS, respectively (using the NoScript add-on). (Script tests pass.)

Upvotes: 1

Related Questions