Javascript Url manipulation and back navigation - javascript

I am updating the url with something like this:
window.history.pushState(null, "Page title", "/?param=" + myParamValue);
This works fine, but when the user hits the back button, the url gets updated but the page does not reload.
I have an ajax routine that updates the content but if possible I don't want to mess with re-implementing back/forward navigation, and I just want the page to reload in case of the user hitting back/forward browser buttons.
Q: Is there a way to force the page to reload the given url on browser back/forward actions from the user?
Bonus Q: also, what if the browser doesn't support window.history.pushState on older browsers? Shall I surround that code in a try/catch block?

if(typeof window.history.pushState === 'function')
//handle your url rewriting
else
//support for older browsers
As for your question about back-button support, the link provided in the comment provides very nice implementations for the feature

You should take a look at this jQuery plugin, it might be useful for you:
http://www.asual.com/jquery/address/
I found it reading this thread:
https://stackoverflow.com/questions/116446/what-is-the-best-back-button-jquery-plugin
I hope it helps.
About the old browser question, I don't think you have to bother with that because you are using ajax, which requires a modern browser too. The main question is: who will visit your web site? If it's mainly people over 40yo, maybe you should bother...
Just my opinion ;)
Edit: Be careful with IE9, it's not handled in it. thx to nbrooks for the info

Related

stop the web page from loading programmatically

I want to create an extension to firefox using addon builder that
stops users from visiting a malicious website; When I see a URL that is
suspicious, I stop the page from loading and ask the user if he really
wants to visit the site. How could I implement that? I am expecting the functionality programmatically, so that I can make an extension.
if(site.is_malicious)
window.stop();
There is an event called beforescriptexecute supported my mozilla ..... Have a look , I think it will work the job for you. But what you desire can be done something like this:
var r=confirm("Are you sure you want to visit this site ?");
if (r==false) { window.stop(); }
You are creating a FF extension right? Why not use greasemonkey or so? You can execute a script BEFORE the page loads(on greasemonkey). when that script is called, you can potentially stop the pageload and throw an error message.

Reload a page once on start for IE9 users with JavaScript

I would like a page to force reload once for IE9 users to clear the cache. I've been experimenting with this function:
location.reload();
The question: is it possibly to target people using IE9 and only reload ONCE on load.
Thankful for any help I can get.
/Linus
It would probably be best if you could devise some strategy which allows you NOT to depend on the browser version.
Having said that, here is a link that will allow you to detect IE9.
reference : stackoverflow similar question
from the link to answer taken
Two options:
1- You can use cookies. Set a cookie when logging in and check for
that during load. Then clear it after performing your initialization
so that next load the check will fail.
2- You can use the address, either as a parameter like ?justLoggedIn,
or a value in the hash after #justLoggedIn. Then check for that and
redirect to the same url minus the justLoggedIn part. The advantage of
the # version is that it doesn't actually reload the page, unlike when
using the ? version.
UPDATE:
reference :stackoverflow similar question
I'd say use hash, like this:
window.onload = function() {
if(!window.location.hash) {
window.location = window.location + '#loaded';
window.location.reload();
}
}
UPDATE 2:
i think you should take a look at this question
i dont know about pjax until now so i dont know alot about it
stackoverflow question
look at http://pjax.heroku.com/in the answers

Detecting browsers that don't support onunload/onbeforeunload

Of all the browsers, it seems that only Opera doesn't support onunload/onbeforeunload events. (It's been fifteen years now, Opera!) Solutions for this issue have been covered many times, here for example: onbeforeunload support detection
Unfortunately, as of Opera 11.51, ("onbeforeunload" in window) == true, but the actual onbeforeunload event is never executed!
My web application needs to send data to server when a user leaves the page; I'm using a synchronous ajax request for this. It looks like I have to resort to using a "Save" button somewhere on the page to cover up for Opera issues. However, I don't want this button to confuse users whose browsers are capable of auto-saving through ajax, so I'd really like the button to only show up in Opera.
Is my only choice browser-detection? The problem is, Opera has an option to disguise itself as other browsers anyway.
I can't reproduce your finding that 'onbeforeunload' in window is true in Opera 11.5x. This is the best way to do it and should still work. Are you sure you haven't left in some definition somewhere, e.g. you've written
onbeforeunload = function (){ ... }
later in the same script that does the feature detection? If you do alert(window.onbeforeunload), what do you see? Could you share a link to the page with the problem?
Opera screwed the pooch on this one. I detect for Opera by looking for window.opera and if it exists, I deny Opera what it can't handle.
Using unload is no good I think, because it occurs too late in the game. Sometimes onbeforeunload is the only thing that'll do the trick. Once again, I just look for opera on the window object, and, if it exists, deny it the things it can't do. :)
PPK talks about it here: http://www.quirksmode.org/js/detect.html
For anyone stumbling across this post, this is a code snippet I use for detecting onbeforeunload support and if the browser doesn't support it I switch to onunload (note the use of jquery, obviously not required). In my case I use this code (and a little extra) to check if any AJAX requests are still active and stop the user navigating away. Keep in mind that using onunload isn't ideal because the browser will still navigate away from the page but at least it gives you a chance to warn the user that data might have been lost and they should go back and check.
You'll notice I'm using the isEventSupported() function available at https://github.com/kangax/iseventsupported for cross browser support detecting available events.
// If the browser supports 'onbeforeunload'
if (isEventSupported('beforeunload', window)) {
$(window).on('beforeunload', function(){
return 'This page is still sending or receiving data from our server, if you recently submitted data on this page please wait a little longer before leaving.';
});
}
// The browser doesn't support 'onbeforeunload' (Such as Opera), do the next best thing 'onunload'.
else {
$(window).on('unload', function(){
alert('This page was still sending or receiving data from our server when you navigated away from it, we would recommend navigating back to the page and ensure your data was submitted.');
});
}
See my answer to a similar / duplicated question. Basically, it sets up detection on the very first page on your domain and stores that detection result for all subsequent pages in localStorage. Including working example code.

How can I write something in browser's address bar with JavaScript after the page is completely loaded?

How can I write something ("hello my client" for example) in the browser's address bar with javascript after the page is completely loaded?
Mean writing something in address bar without entering - is it possible?
It seems we can do this job with JavaScript, if not can we do that with server side code?
How?
This is possible, but only the part after the hostname:
history.pushState(null, "page 2", '/foo.html');
Try this in your javascript console, this effectively changes the current path with /foo.html. (It's a new html5 feature, and is available in recent browsers only.)
See mozilla docs: https://developer.mozilla.org/en/DOM/Manipulating_the_browser_history#Adding_and_modifying_history_entries
Browser Compatibility
Why?
This is used to make ajax sites history/bookmark/link friendly by updating the URL as the content is updated. Currently most sites do this by only changing the hash part of the URL (e.g. Twitter with their #!.)
For instance Github uses this for their code browser: https://github.com/blog/760-the-tree-slider
Maybe its already answered # Change the URL in the browser without loading the new page using JavaScript .
You can set location.hash, but you can't replace the entire URI.
The reason this is not possible is it presents a security violation. This is why phishers write a gif file over where they believe the address bar will be.
My question is why would you want to do this? The only reason I can think of is you want to make someone think they are at http://Iamreallyyourbank.com when they are at http://IamStealingYourMoney.com, which is why the security is in place.
This is not possible. You cannot change the URL displayed in the browser. Not only would it be a horrible security practice, it would be a violation of trust to the people visiting your site.

Take Screenshot of Browser via JavaScript (or something else)

For support reasons I want to be able for a user to take a screenshot of the current browser window as easy as possible and send it over to the server.
Any (crazy) ideas?
That would appear to be a pretty big security hole in JavaScript if you could do this. Imagine a malicious user installing that code on your site with a XSS attack and then screenshotting all of your daily work. Imagine that happening with your online banking...
However, it is possible to do this sort of thing outside of JavaScript. I developed a Swing application that used screen capture code like this which did a great job of sending an email to the helpdesk with an attached screenshot whenever the user encountered a RuntimeException.
I suppose you could experiment with a signed Java applet (shock! horror! noooooo!) that hung around in the corner. If executed with the appropriate security privileges given at installation it might be coerced into executing that kind of screenshot code.
For convenience, here is the code from the site I linked to:
import java.awt.Dimension;
import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import javax.imageio.ImageIO;
import java.io.File;
...
public void captureScreen(String fileName) throws Exception {
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
Rectangle screenRectangle = new Rectangle(screenSize);
Robot robot = new Robot();
BufferedImage image = robot.createScreenCapture(screenRectangle);
ImageIO.write(image, "png", new File(fileName));
}
...
Please see the answer shared here for a relatively successful implementation of this:
https://stackoverflow.com/a/6678156/291640
Utilizing:
https://github.com/niklasvh/html2canvas
You could try to render the whole page in canvas and save this image back to server. have fun :)
A webpage can't do this (or at least, I would be very surprised if it could, in any browser) but a Firefox extension can. See https://developer.mozilla.org/en/Drawing_Graphics_with_Canvas#Rendering_Web_Content_Into_A_Canvas -- when that page says "Chrome privileges" that means an extension can do it, but a web page can't.
Seems to me that support needs (at least) the answers for two questions:
What does the screen look like? and
Why does it look that way?
A screenshot -- a visual -- is very necessary and answers the first question, but it can't answer the second.
As a first attempt, I'd try to send the entire page up to support. The support tech could display that page in his browser (answers the first question); and could also see the current state of the customer's html (helps to answer the second question).
I'd try to send as much of the page as is available to the client JS by way of AJAX or as the payload of a form. I'd also send info not on the page: anything that affects the state of the page, like cookies or session IDs or whatever.
The cust might have a submit-like button to start the process.
I think that would work. Let's see: it needs some CGI somewhere on the server that catches the incoming user page and makes it available to support, maybe by writing a disk file. Then the support person can load (or have loaded automatically) that same page. All the other info (cookies and so on) can be put into the page that support sees.
PLUS: the client JS that handles the submit-button onclick( ) could also include any useful JS variable values!
Hey, this can work! I'm getting psyched :-)
HTH
-- pete
I've seen people either do this with two approaches:
setup a separate server for screenshotting and run a bunch of firefox instances on there, check out these two gem if you're doing it in ruby: selenium-webdriver and headless
use a hosted solution like http://url2png.com (way easier)
You can also do this with the Fireshot plugin. I use the following code (that I extracted from the API code so I don't need to include the API JS) to make a direct call to the Fireshot object:
var element = document.createElement("FireShotDataElement");
element.setAttribute("Entire", true);
element.setAttribute("Action", 1);
element.setAttribute("Key", "");
element.setAttribute("BASE64Content", "");
element.setAttribute("Data", "C:/Users/jagilber/Downloads/whatev.jpg");
if (typeof(CapturedFrameId) != "undefined")
element.setAttribute("CapturedFrameId", CapturedFrameId);
document.documentElement.appendChild(element);
var evt = document.createEvent("Events");
evt.initEvent("capturePageEvt", true, false);
element.dispatchEvent(evt);
Note: I don't know if this functionality is only available for the paid version or not.
Perhaps http://html2canvas.hertzen.com/ could be used. Then you can capture the display and then process it.
You might try PhantomJs, a headlesss browsing toolkit.
http://phantomjs.org/
The following Javascript example demonstrates basic screenshot functionality:
var page = require('webpage').create();
page.settings.userAgent = 'UltimateBrowser/100';
page.viewportSize = { width: 1200, height: 1200 };
page.clipRect = { top: 0, left: 0, width: 1200, height: 1200 };
page.open('https://google.com/', function () {
page.render('output.png');
phantom.exit();
});
I understand this post is 5 years old, but for the sake of future visits I'll add my own solution here which I think solves the original post's question without any third-party libraries apart from jQuery.
pageClone = $('html').clone();
// Make sure that CSS and images load correctly when opening this clone
pageClone.find('head').append("<base href='" + location.href + "' />");
// OPTIONAL: Remove potentially interfering scripts so the page is totally static
pageClone.find('script').remove();
htmlString = pageClone.html();
You could remove other parts of the DOM you think are unnecessary, such as the support form if it is in a modal window. Or you could choose not to remove scripts if you prefer to maintain some interaction with dynamic controls.
Send that string to the server, either in a hidden field or by AJAX, and then on the server side just attach the whole lot as an HTML file to the support email.
The benefits of this are that you'll get not just a screenshot but the entire scrollable page in its current form, plus you can even inspect and debug the DOM.
Print Screen? Old school and a couple of keypresses, but it works!
This may not work for you, but on IE you can use the snapsie plugin. It doesn't seem to be in development anymore, but the last release is available from the linked site.
i thing you need a activeX controls. without it i can't imagine. you can force user to install them first after the installation on client side activex controls should work and you can capture.
We are temporarily collecting Ajax states, data in form fields and session information. Then we re-render it at the support desk. Since we test and integrate for all browsers, there are hardly any support cases for display reasons.
Have a look at the red button at the bottom on holidaycheck
Alternatively there is html2canvas of Google. But it is only applicable for never browsers and I've never tried it.
In JavaScript? No. I do work for a security company (sort of NetNanny type stuff) and the only effective way we've found to do screen captures of the user is with a hidden application.

Categories

Resources