How to detect if JavaScript is disabled? - javascript

There was a post this morning asking about how many people disable JavaScript. Then I began to wonder what techniques might be used to determine if the user has it disabled.
Does anyone know of some short/simple ways to detect if JavaScript is disabled? My intention is to give a warning that the site is not able to function properly without the browser having JS enabled.
Eventually I would want to redirect them to content that is able to work in the absence of JS, but I need this detection as a placeholder to start.

I'd like to add my .02 here. It's not 100% bulletproof, but I think it's good enough.
The problem, for me, with the preferred example of putting up some sort of "this site doesn't work so well without Javascript" message is that you then need to make sure that your site works okay without Javascript. And once you've started down that road, then you start realizing that the site should be bulletproof with JS turned off, and that's a whole big chunk of additional work.
So, what you really want is a "redirection" to a page that says "turn on JS, silly". But, of course, you can't reliably do meta redirections. So, here's the suggestion:
<noscript>
<style type="text/css">
.pagecontainer {display:none;}
</style>
<div class="noscriptmsg">
You don't have javascript enabled. Good luck with that.
</div>
</noscript>
...where all of the content in your site is wrapped with a div of class "pagecontainer". The CSS inside the noscript tag will then hide all of your page content, and instead display whatever "no JS" message you want to show. This is actually what Gmail appears to do...and if it's good enough for Google, it's good enough for my little site.

I assume you're trying to decide whether or not to deliver JavaScript-enhanced content. The best implementations degrade cleanly, so that the site will still operate without JavaScript. I also assume that you mean server-side detection, rather than using the <noscript> element for an unexplained reason.
There is no good way to perform server-side JavaScript detection. As an alternative it is possible to set a cookie using JavaScript, and then test for that cookie using server-side scripting upon subsequent page views. However this would be unsuitable for deciding what content to deliver, as it would not distinguish visitors without the cookie from new visitors or from visitors who did not accept the JavaScript set cookie.

noscript blocks are executed when JavaScript is disabled, and are typically used to display alternative content to that you've generated in JavaScript, e.g.
<script type="javascript">
... construction of ajaxy-link, setting of "js-enabled" cookie flag, etc..
</script>
<noscript>
Next Page
</noscript>
Users without js will get the next_page link - you can add parameters here so that you know on the next page whether they've come via a JS/non-JS link, or attempt to set a cookie via JS, the absence of which implies JS is disabled. Both of these examples are fairly trivial and open to manipulation, but you get the idea.
If you want a purely statistical idea of how many of your users have javascript disabled, you could do something like:
<noscript>
<img src="no_js.gif" alt="Javascript not enabled" />
</noscript>
then check your access logs to see how many times this image has been hit. A slightly crude solution, but it'll give you a good idea percentage-wise for your user base.
The above approach (image tracking) won't work well for text-only browsers or those that don't support js at all, so if your userbase swings primarily towards that area, this mightn't be the best approach.

This is what worked for me: it redirects a visitor if javascript is disabled
<noscript><meta http-equiv="refresh" content="0; url=whatyouwant.html" /></noscript>

I'd suggest you go the other way around by writing unobtrusive JavaScript.
Make the features of your project work for users with JavaScript disabled, and when you're done, implement your JavaScript UI-enhancements.
https://en.wikipedia.org/wiki/Unobtrusive_JavaScript

If your use case is that you have a form (e.g., a login form) and your server-side script needs to know if the user has JavaScript enabled, you can do something like this:
<form onsubmit="this.js_enabled.value=1;return true;">
<input type="hidden" name="js_enabled" value="0">
<input type="submit" value="go">
</form>
This will change the value of js_enabled to 1 before submitting the form. If your server-side script gets a 0, no JS. If it gets a 1, JS!

<noscript> isn't even necessary, and not to mention not supported in XHTML.
Working Example:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Frameset//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-frameset.dtd">
<html>
<head>
<title>My website</title>
<style>
#site {
display: none;
}
</style>
<script src="http://code.jquery.com/jquery-latest.min.js "></script>
<script>
$(document).ready(function() {
$("#noJS").hide();
$("#site").show();
});
</script>
</head>
<body>
<div id="noJS">Please enable JavaScript...</div>
<div id="site">JavaScript dependent content here...</div>
</body>
</html>
In this example, if JavaScript is enabled, then you see the site. If not, then you see the "Please enable JavaScript" message. The best way to test if JavaScript is enabled, is to simply try and use JavaScript! If it works, it's enabled, if not, then it's not...

Use a .no-js class on the body and create non javascript styles based on .no-js parent class.
If javascript is disabled you will get all the non javascript styles,
if there is JS support the .no-js class will be replaced giving you all the styles as usual.
document.body.className = document.body.className.replace("no-js","js");
trick used in HTML5 boilerplate http://html5boilerplate.com/ through modernizr but you can use one line of javascript to replace the classes
noscript tags are okay but why have extra stuff in your html when it can be done with css

just a bit tough but (hairbo gave me the idea)
CSS:
.pagecontainer {
display: none;
}
JS:
function load() {
document.getElementById('noscriptmsg').style.display = "none";
document.getElementById('load').style.display = "block";
/* rest of js*/
}
HTML:
<body onload="load();">
<div class="pagecontainer" id="load">
Page loading....
</div>
<div id="noscriptmsg">
You don't have javascript enabled. Good luck with that.
</div>
</body>
would work in any case right?
even if the noscript tag is unsupported (only some css required)
any one knows a non css solution?

You can use a simple JS snippet to set the value of a hidden field. When posted back you know if JS was enabled or not.
Or you can try to open a popup window that you close rapidly (but that might be visible).
Also you have the NOSCRIPT tag that you can use to show text for browsers with JS disabled.

You'll want to take a look at the noscript tag.
<script type="text/javascript">
...some javascript script to insert data...
</script>
<noscript>
<p>Access the data.</p>
</noscript>

Because I always want to give the browser something worthwhile to look at I often use this trick:
First, any portion of a page that needs JavaScript to run properly (including passive HTML elements that get modified through getElementById calls etc.) are designed to be usable as-is with the assumption that there ISN'T javaScript available. (designed as if it wasn't there)
Any elements that would require JavaScript, I place inside a tag something like:
<span name="jsOnly" style="display: none;"></span>
Then at the beginning of my document, I use .onload or document.ready within a loop of getElementsByName('jsOnly') to set the .style.display = ""; turning the JS dependent elements back on. That way, non-JS browsers don't ever have to see the JS dependent portions of the site, and if they have it, it appears immediately when it's ready.
Once you are used to this method, it's fairly easy to hybridize your code to handle both situations, although I am only now experimenting with the noscript tag and expect it will have some additional advantages.

The noscript tag works well, but will require each additional page request to continue serving useless JS files, since essentially noscript is a client side check.
You could set a cookie with JS, but as someone else pointed out, this could fail. Ideally, you'd like to be able to detect JS client side, and without using cookies, set a session server side for that user that indicates is JS is enabled.
A possibility is to dynamically add a 1x1 image using JavaScript where the src attribute is actually a server side script. All this script does is saves to the current user session that JS is enabled ($_SESSION['js_enabled']). You can then output a 1x1 blank image back to the browser. The script won't run for users who have JS disabled, and hence the $_SESSION['js_enabled'] won't be set. Then for further pages served to this user, you can decide whether to include all of your external JS files, but you'll always want to include the check, since some of your users might be using the NoScript Firefox add-on or have JS disabled temporarily for some other reason.
You'll probably want to include this check somewhere close to the end of your page so that the additional HTTP request doesn't slow down the rendering of your page.

Add this to the HEAD tag of each page.
<noscript>
<meta http-equiv="refresh" runat="server" id="mtaJSCheck" content="0;logon.aspx" />
</noscript>
So you have:
<head>
<noscript>
<meta http-equiv="refresh" runat="server" id="mtaJSCheck" content="0;logon.aspx" />
</noscript>
</head>
With thanks to Jay.

A common solution is to the meta tag in conjunction with noscript to refresh the page and notify the server when JavaScript is disabled, like this:
<!DOCTYPE html>
<html lang="en">
<head>
<noscript>
<meta http-equiv="refresh" content="0; /?javascript=false">
</noscript>
<meta charset="UTF-8"/>
<title></title>
</head>
</html>
In the above example when JavaScript is disabled the browser will redirect to the home page of the web site in 0 seconds. In addition it will also send the parameter javascript=false to the server.
A server side script such as node.js or PHP can then parse the parameter and come to know that JavaScript is disabled. It can then send a special non-JavaScript version of the web site to the client.

This is the "cleanest" solution id use:
<noscript>
<style>
body *{ /*hides all elements inside the body*/
display: none;
}
h1{ /* even if this h1 is inside head tags it will be first hidden, so we have to display it again after all body elements are hidden*/
display: block;
}
</style>
<h1>JavaScript is not enabled, please check your browser settings.</h1>
</noscript>

If javascript is disabled your client-side code won't run anyway, so I assume you mean you want that info available server-side. In that case, noscript is less helpful. Instead, I'd have a hidden input and use javascript to fill in a value. After your next request or postback, if the value is there you know javascript is turned on.
Be careful of things like noscript, where the first request may show javascript disabled, but future requests turn it on.

You might, for instance, use something like document.location = 'java_page.html' to redirect the browser to a new, script-laden page. Failure to redirect implies that JavaScript is unavailable, in which case you can either resort to CGI ro utines or insert appropriate code between the tags. (NOTE: NOSCRIPT is only available in Netscape Navigator 3.0 and up.)
credit
http://www.intranetjournal.com/faqs/jsfaq/how12.html

A technique I've used in the past is to use JavaScript to write a session cookie that simply acts as a flag to say that JavaScript is enabled. Then the server-side code looks for this cookie and if it's not found takes action as appropriate. Of course this technique does rely on cookies being enabled!

I think you could insert an image tag into a noscript tag and look at the stats how many times your site and how often this image has been loaded.

People have already posted examples that are good options for detection, but based on your requirement of "give warning that the site is not able to function properly without the browser having JS enabled". You basically add an element that appears somehow on the page, for example the 'pop-ups' on Stack Overflow when you earn a badge, with an appropriate message, then remove this with some Javascript that runs as soon as the page is loaded (and I mean the DOM, not the whole page).

code inside <noscript> tags will be executed when there is no js enabled in browser.
we can use noscript tags to display msg to turn on JS as below.
<noscript>
<h1 style="text-align: center;">
To view this page properly, please
enable JavaScript and reload the page
</h1>
</noscript>
while keeping our website content inside body as hidden. as below
<body>
<div id="main_body" style="display: none;">
website content.
</div>
</body>
now if JS is turned on you can just make the content inside your main_body visible as below
<script type="text/javascript">
document.getElementById("main_body").style.display="block";
</script>

Why don't you just put a hijacked onClick() event handler that will fire only when JS is enabled, and use this to append a parameter (js=true) to the clicked/selected URL (you could also detect a drop down list and change the value- of add a hidden form field). So now when the server sees this parameter (js=true) it knows that JS is enabled and then do your fancy logic server-side.
The down side to this is that the first time a users comes to your site, bookmark, URL, search engine generated URL- you will need to detect that this is a new user so don't look for the NVP appended into the URL, and the server would have to wait for the next click to determine the user is JS enabled/disabled. Also, another downside is that the URL will end up on the browser URL and if this user then bookmarks this URL it will have the js=true NVP, even if the user does not have JS enabled, though on the next click the server would be wise to knowing whether the user still had JS enabled or not. Sigh.. this is fun...

To force users to enable JavaScripts, I set 'href' attribute of each link to the same document, which notifies user to enable JavaScripts or download Firefox (if they don't know how to enable JavaScripts). I stored actual link url to the 'name' attribute of links and defined a global onclick event that reads 'name' attribute and redirects the page there.
This works well for my user-base, though a bit fascist ;).

You don't detect whether the user has javascript disabled (server side or client). Instead, you assume that javascript is disabled and build your webpage with javascript disabled. This obviates the need for noscript, which you should avoid using anyway because it doesn't work quite right and is unnecessary.
For example, just build your site to say <div id="nojs">This website doesn't work without JS</div>
Then, your script will simply do document.getElementById('nojs').style.display = 'none'; and go about its normal JS business.

Check for cookies using a pure server side solution i have introduced here then check for javascript by dropping a cookie using Jquery.Cookie and then check for cookie this way u check for both cookies and javascript

In some cases, doing it backwards could be sufficient. Add a class using javascript:
// Jquery
$('body').addClass('js-enabled');
/* CSS */
.menu-mobile {display:none;}
body.js-enabled .menu-mobile {display:block;}
This could create maintenance issues on anything complex, but it's a simple fix for some things. Rather than trying to detect when it's not loaded, just style according to when it is loaded.

I would like to add my solution to get reliable statistics on how many real users visit my site with javascript disabled over the total users. The check is done one time only per session with these benefits:
Users visiting 100 pages or just 1 are counted 1 each. This allows to focus on single users, not pages.
Does not break page flow, structure or semantic in anyway
Could logs user agent. This allow to exclude bots from statistics, such as google bot and bing bot which usually have JS disabled! Could also log IP, time etc...
Just one check per session (minimal overload)
My code uses PHP, mysql and jquery with ajax but could be adapted to other languanges:
Create a table in your DB like this one:
CREATE TABLE IF NOT EXISTS `log_JS` (
`logJS_id` int(11) NOT NULL AUTO_INCREMENT,
`data_ins` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`session_id` varchar(50) NOT NULL,
`JS_ON` tinyint(1) NOT NULL DEFAULT '0',
`agent` varchar(255) DEFAULT NULL,
PRIMARY KEY (`logJS_id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
Add this to every page after using session_start() or equivalent (jquery required):
<? if (!isset($_SESSION["JSTest"]))
{
mysql_query("INSERT INTO log_JS (session_id, agent) VALUES ('" . mysql_real_escape_string(session_id()) . "', '" . mysql_real_escape_string($_SERVER['HTTP_USER_AGENT']). "')");
$_SESSION["JSTest"] = 1; // One time per session
?>
<script type="text/javascript">
$(document).ready(function() { $.get('JSOK.php'); });
</script>
<?
}
?>
Create the page JSOK.php like this:
<?
include_once("[DB connection file].php");
mysql_query("UPDATE log_JS SET JS_ON = 1 WHERE session_id = '" . mysql_real_escape_string(session_id()) . "'");

I've figured out another approach using css and javascript itself.
This is just to start tinkering with classes and ids.
The CSS snippet:
1. Create a css ID rule, and name it #jsDis.
2. Use the "content" property to generate a text after the BODY element. (You can style this as you wish).
3 Create a 2nd css ID rule and name it #jsEn, and stylize it. (for the sake of simplicity, I gave to my #jsEn rule a different background color.
<style>
#jsDis:after {
content:"Javascript is Disable. Please turn it ON!";
font:bold 11px Verdana;
color:#FF0000;
}
#jsEn {
background-color:#dedede;
}
#jsEn:after {
content:"Javascript is Enable. Well Done!";
font:bold 11px Verdana;
color:#333333;
}
</style>
The JavaScript snippet:
1. Create a function.
2. Grab the BODY ID with getElementById and assign it to a variable.
3. Using the JS function 'setAttribute', change the value of the ID attribute of the BODY element.
<script>
function jsOn() {
var chgID = document.getElementById('jsDis');
chgID.setAttribute('id', 'jsEn');
}
</script>
The HTML part.
1. Name the BODY element attribute with the ID of #jsDis.
2. Add the onLoad event with the function name. (jsOn()).
<body id="jsDis" onLoad="jsOn()">
Because of the BODY tag has been given the ID of #jsDis:
- If Javascript is enable, it will change by himself the attribute of the BODY tag.
- If Javascript is disable, it will show the css 'content:' rule text.
You can play around with a #wrapper container, or with any DIV that use JS.
Hope this helps to get the idea.

Detect it in what? JavaScript? That would be impossible. If you just want it for logging purposes, you could use some sort of tracking scheme, where each page has JavaScript that will make a request for a special resource (probably a very small gif or similar). That way you can just take the difference between unique page requests and requests for your tracking file.

Related

How to reload part of a web page using iframe instead of ajax?

The reason I don't want to use ajax to do this is because the part I want to refresh is actually a commenting plugin implemented by other. I just put a snippet of script they provided in my html code and it shows a commenting part under my articles. As it's not a live commenting one, I want to add a refresh button next to it to enable users to just refresh the commenting part to get the latest comments without need for reloading the whole page.
Therefore, I think maybe iframe is an option for me. But the problem is I need to specify the src attribute of iframe. I don't know what value I should use because all I have is just a snippet of script. Can someone give me any idea on this?
By the way, the code snippet is as follows:
<div id="uyan_frame"></div>
<script type="text/javascript" id="UYScript" src="http://v1.uyan.cc/js/iframe.js?UYUserId=1674366" async=""></script>
Just create a html page with the script you talked inside about and use this file in the iframe src attribute.
You can put the snippet above in an html file like this
<!DOCTYPE html>
<html>
<body>
<div id="uyan_frame"></div>
<script type="text/javascript" id="UYScript" src="http://v1.uyan.cc/js/iframe.js?UYUserId=1674366" async=""></script>
</body>
</html>
And then use that file as the src of your iFrame, which you can refresh using javascript.
That said, just because you can do something doesn't mean you should do something. This is a really hacky way of doing what you're trying to do. A few alternative options:
Understand what the script you're using is doing, and work with it. Judging by the name of the script and div in the snippet, it may be creating an iframe to begin with. If thats the case, why not just figure out what that iFrame is called using your browsers debug it and refresh it manually, or modify the script to do so?
Use a live updating framework- This may not be possible for you, I don't know your constraints, but there are plenty of great commenting frameworks out there that do live updates. For instance Disqus comes to mind. Other examples are facebook comments or you could embed a reference to an external site like branch
Use Ajax - I'm a bit unclear on whether this is your script that you're writing, or a 3rd party script. If it is your script, then use the generally accepted methods for doing this type of work, unless you have a really great reason not too. You'll get better support from others, you'll gain more generally applicable experience, and for the most part, best practices gain that name for a reason. People use "ajax" methods for live updating pages because its effective and useful. Frames have become much less common on the web because they're clunky and make it difficult for different parts of the page to interact. If you don't have a great reason not to use the common practice, its usually your best bet.
You could do this :
var iframe = document.getElementById('your_frame_id');
iframe.src = iframe.src;
set the iframe src to its value again, this will cause the frame to refresh, and will work with cross domain frames

How to stop page load in html static page

Is there in HTML (javascript) or other static html tech
can:
Stop page loading (if browser does not download yet)
Stop page rendering (from where the code placed)
Stop javascript executed (from where the code placed)
Simply put, is there a code like
<script>window.StopWhateverBelow()</script>
To let browser totally ignore whatever below the code.
UPDATE
I understand the browser may already download the whole thing. What I want is, from the code, page should stopped, for example: if I put the code just after <body> visitor should see blank page, if I put the code in middle of the page, page should be just half like you pressed ESC
ANSWER
As bukko suggested, comments done the trick. But not full, just half
If you put <!-- in html page, the rest will be ignored. And in Javascript
document.write('<!--');
Done the trick.
For about make sense:
Here is how this code make sense: when you page load some offpage script, the script is dynamic. When the script code found something wrong (or match some condition), you have one more option to stop the page from rendering, loading, download...
You could do window.stop(); for most browsers besides Internet Explorer. For IE, I had to use document.execCommand('Stop');
If you already have html comments on your page, #bukko's solution doesn't fully work. Stuff after the html comment will get rendered normally.
Something else to try is:
document.write('<script type="text/undefined">')
The rest of the document gets interpreted as part of the script tag, and because the script isn't text/javascript, it gets ignored.
Worked for me, thought I'd share it.
Edit
I've seen the script trick not work in Chrome.
This does work, but I have not done extensive browser testing:
document.write('<style type="text/undefined">')
window.stop(); //works in all browsers but IE
if ($.browser.msie) {document.execCommand("Stop");}; //works in IE,
document.execCommand works in IE, however it does stop some of FF, NS and some other browsers' functions. Like displaying GIF's animation for example. Using "if browser is IE" makes these two codes work perfectly in all browsers.
Well, there is:
<!--
terminated by
-->
for HTML, but scripts will ignore this.
What you are asking makes no logical sense. Simply for two reasons:
Data is ALREADY sent to the user (HTML / JS) so even tho if you COULD hide content, the data would sitll be there for a user to see (if they view source for instance).
Why would you stop 'execution' of a page? It loads simple html structure and reults in a visual display, you should focus on the server site (php for instance) to hide or not send the content in the first place.
If you want to visually hide elements tho, you could use CSS styles (hide divs or the like) with simply adding style="display:none;" to a div like so:
<div style="display:none;">
This text will be downloaded by the user, but hidden from view due to CSS inline style
</div>
If you want to add commenting (thats just for your reference), then use comment formatting:
<!-- this is a comment and will not show up to a user -->
Reference for comments: http://htmlhelp.com/reference/wilbur/misc/comment.html
put window.Stop() wherever you want to stop the page from getting renderred
You could also hide the body like that:
var style = document.createElement("style");
style.innerHTML="body { display:none !important; }";
document.getElementsByTagName("HEAD")[0].appendChild(style);
HTML is static content so the server reads whatever you have written in the file unless you comment it out. For a dynamic file like what you are asking for you need to use php which can do this type of thing.
Just not much related to the question, but I thought it may be useful for some persons. If you want to jump to other page during page loading use window.location = "somepage.html"; or you can redirect users to the previous page: window.history.go(-1); Useful in JavaScript conditional statements
If you are using ASP or PHP, HTTP protocol automatically stops but HTTPS protocol don't stop automatically.
To stop it use:
In ASP:
dim r= accept.secure.protocol
r.onload=window.callback('c')
//to firefox,opera,safari
new clientObject(r).access()
// to chrome,ie
forEachElement(a==null);
PHP code:
$a.window ;
All this scripts sends the browserstring "elementcast" by post method
The stop methods can break things that have already started to load.
If you want to load everything above a certain point and skip everything below a certain point:
<p>Everything works above this point.</p>
<pre style="display: none !important;">
<p>As long as the PRE tag remains open,
nothing works below this point</p>
<script>document.write('Nope');

Showing a demo of my CSS on any website

I have developed a small component which can be put in to any website. Now, I want to develop a code that could demonstrate how would my component look like on any website.
So, the person would come to my page and put in his URL and then my code should embed my custom JS/CSS in to the downloaded HTML and display it. Something like this.
Here, like the feedback tab, I want to show my component any where on that page.
Try a bookmarklet.
Create a piece of javascript that adds your code into the page such as the following:
javascript:(function(){var%20script=document.createElement('script');script.src='http://www.example.org/js/example.js';document.getElementsByTagName('head')[0].appendChild(script);})()
Add it as the href of a link like so:
Link Text Here
Tell your users to drag the link to their bookmark toolbar and click on it on different websites to try your code out.
Some examples: http://www.reclaimprivacy.org/, http://www.readability.com/bookmarklets
In the example you linked, they are requesting the page specified in the url querystring parameter on the server, and then doing more or less the following steps:
In the <head> tag they are adding a <base href="url" /> tag to the document. The base tag will make any relative links in the document treat the value in the href attribute as their root. This is how they are getting around broken css / images. (The base tag is supported by all browsers)
At the end of the document (IE the </body> tag) they are injecting the javascript that runs their demos.
They serve the modified HTML requested to the browser.
All of this is pretty straight forward in implementation. You could use regular expressions to match the <head> and </body> tags for steps 1 and 2 respectively. Depending on the server platform how you actually request the page will vary, but here are some links to get you started:
C# - HttpWebRequest object documentation
PHP - HttpRequest::send
Nathan's answer is the closest to how we have done the demo feature at WebEngage. To make such a demo functional, you'll need to create a Javascript widget that can be embedded on third party sites. syserr0r's answer on creating a bookmarklet is the simplest approach to do so. Our's is a JAVA backend and we use HttpClient to fetch the responses. As Nathan suggested, we parse the response, sanitize it and add our widget Javascript to the response. The widget JS code takes it on from there to render the Feedback tab and load a demo short survey.
Disclosure: I am a co-founder and ceo at WebEngage.
You can not do this with JQuery due to cross site scripting restrictions.
I suggest you write a PHP script that downloads the URL specified by the user and includes your widget code and then echo it back to the user.
I recommend using bookmarklets. I've made a bookmarklet generator for adding jQuery-enabled bookmarklets to a page to make development easier.
There's a caliper bookmarklet on the page that you can mess around with just to show an example of it working.
Full disclosure, this is something I've made, I'm not trying to be spammy as I think it's relevant: zbooks
You could make an iframe page, which loads their page in the iframe, and uses javascript to inject your code into the iframe.
Here is my approach...
http://jsfiddle.net/L2kEf/
html
<iframe src="http://www.bing.com"></iframe>
<div>I am div</div>
css
div { background: red; position: absolute; top: 20px; width: 100px; left:20px;}
iframe{width: 100%; height: 500px;}
you can add javascript/jquery too, so you could do something like,
jQuery //not 100% sure it would work coz of cross browser thingy, but you know, worth a try.
$('div').click(function (){
$('iframe').contents().html('changed');///
});
if this can't change any of the contents, you can display a dialog, to say it would normally work if it was in your website, then use #syserr0r approach for bookmarked users, for better results, since you are offering this kinda services, to developers, im sure they would know about bookmarking, my approach would be rarely used :) so hope it helps.
I had a problem of a similiar nature, and the main obstacle is the cross-domain policy.
You have to ask the user to put your code in a <script src="..."> or create a proxy solution that would add your code for them.
I went for the proxy and here are my observations:
it's easy to create a basic proxy in php - there are some php proxies on sourceforge and Ben Alman has created a simple php proxy for AJAX. Based on those I was able to create a php proxy altering the content properly in one day.
after that I spent a lot of time making it work with more and more sites with issues. You can never create a perfect proxy.
As an alternative (sa long as you are non-commercial) you can use http://www.jmarshall.com/tools/cgiproxy/ and put the site in an iframe and then do whatever you want to do with the iframes document, as it's in your domain thanks to the proxy. You can access iframeDOMnode.contentWindow.document then, etc.
You can create a Crossrider extension which your users can download.
Then simply add this to your App/Extension code:
appAPI.dom.addRemoteJS("http://yourdomain.com/file.js")
Your users can then download the extension (it works cross-browser for Internet Explorer, Chrome and Firefox) and it will load your JS code on every page load.
You can get an approximation of what it will look like using a iframe. Take a look at that link for an example.
http://jsfiddle.net/jzaun/5PjRy/
The issue with this appoch is that you can't move your DIV(s) when the page scrolls, they are in effect just floating over the iframe. There is no way around this as cross-domain scripting wont let you access the iframe's document to monitor scroll events.
The only other option you have for a better fitting example would be to load the page from the server side in whatever scripting language you are using and load that into the iframe (or into a div, etc.) and you can use javascript all you want as the page is coming from your domain.
For your example of what will your widget look like I imagine floating your DIV(s) over an iframe would give enough of an idea.
Please note the example you gave is using the server side method, not the iframe method.
I agree with the bookmarklet strategy.
I'm a fan of http://bookmarklets.heroku.com/, which lets you generate bookmarklets easily, inject jQuery, etc.

Javascript to reload page with javascript disabled

I am interacting with a webpage that I need to have java scripting alternatively disabled and then enabled.
I can't change the scripting setting in the browser to disable scripting since some of the website requires scripting be enable to work properly.
The program I am using allows me to execute a javascript but I can't figure out how to code a script that load a page with javascript disabled.
Any ideas how I can run a javascript to disable scripts on the page?
Thanks for all the feedback - A little more background might help.
I am using a program to create a bot that automates some of my repetitive tasks. The problem is that my program doesn't recognize the links generated by java scripting on the first two pages of the process so I have to have scripting disabled in my browser. Unfortunately on the last and final page of the process scripting is required to render a menu.
I am have request with their development team to change this final page so its viewable without scripts but in the meantime I've still got this problem.
I believe I'll be able to make this work by opening a new browser window, executing the window onload script for the first two steps then going back to a regular window for the final step. I'll let you know if it works.
And yes this is for a personal project and the site owners are aware of my attempts to automate their pages with my software.
You can't disable scripts using javascript.
Disabling javascript is something that is done within the browser configuration.
If your script is run outside the browser, you may be able to point it at 2 different browsers, one that has javascript enabled and one that doesn't.
Alternatively, some browsers (Firefox) have the notion of "Profiles" that you can start directly - so you could have one profile with javascript enabled and one without it.
The only way you could force a reload without Javascript is via a meta-refresh in the page's <head> block:
<meta http-equiv="refresh" content="600;url=http://address.to.your/page" />
or output some text to tell people to "click here to refresh".
Basically you're asking "how can I drive my car somewhere after I remove the engine".
You could look into an add-on for your browser that disables scripts.
Particularly one that can disable them on only a few pages per website, and not the whole site.
...with great difficulty!
However, if you can put this right at the top of the document (preferably inside an if statement acting upon whatever trigger you're using to enable/disable JavaScript):
<script>
window.onload = function()
{
var contents = document.getElementsByTagName('XMP')[0].innerHTML;
contents = contents.replace(/<script/gi, '<xscript');
contents = contents.replace(/<\/script/gi, '</xscript');
contents = contents.replace(/ on([a-z]+=)/gi, ' *$1');
document.open();
document.write(contents);
document.close();
}
document.write("<xmp>");
</script>
That just might do the job. Except for JavaScript running in IFRAMES and things like that. And except for the unlikely scenario that you're actually using the lesser-spotted XMP element somewhere within your pages.
Not working in Safari. Is this just for your own personal use?

How do I show content when Javascript isn't available, hide it when javascript is available and not flicker in either case?

I have a simple form for shipping options and I am using javascript to auto submit the form when someone selects a new option from the drop down list.
In order to support browsers without javascript there is also a button to submit the form. This button is hidden using javascript.
However, this means my button is visible for a brief period of time and can cause a flicker as the rest of the content is reformatted.
Can anyone suggest a way of creating the button so it starts off hidden, but is made visible only if javascript is not available? eg, start out with display:none; and magically change to display:block; if and only if there is no javascript.
Just put anything inside <noscript> ... </noscript> tags and then it will only appear if JavaScript is not enabled/available.
It depends on how you are hiding it, are you using a DOM ready or a window ready? Window ready waits for all images to download, which is generally far too long.
For accessibility, reasons, I'd hide it on DOM loaded. But to ensure it won't show up, you could put it in a noscript element
<noscript>
<input type="submit" />
</noscript>
As for your last paragraph, nothing like that can happen in the absence of JavaScript.
Just write unobtrusive javascript: http://icant.co.uk/articles/seven-rules-of-unobtrusive-javascript/.
What you do is write your page as a normal page, but, then use the code at the bottom to start the javascript, and start editing the page to make it more interactive. The beauty of this is that if they have javascript turned off the page is normal, but, if they have it on, then you can gracefully add more features.
I am not a big fan of the option as that may mean lots of extra code to be downloaded that isn't needed.
On this page look at comment 5 for a good solution to be able to make changes before anything is actually displayed:
http://dean.edwards.name/weblog/2006/06/again/
You could use script before and after the submit button to write hidden div element start and end tags.
One option would be to start with your button shown, and then modify its CSS from JavaScript:
<head>
...
<link rel="stylesheet" href="style.css" type="text/css" charset="utf-8">
<script>
document.styleSheets[0].addRule(".hideMe", "display:none");
</script>
...
</head>
Modifying the stylesheet instead of the button (and putting this code outside of an onload) ensures that it'll be hidden before the button is drawn.

Categories

Resources