I'm having problems with history object and iframes in javascript/html5. I wrote a simple project to describe my problem:
http://dktest.evermight.com/
It's a page with an iframe and a next button. Every time you click next, it loads a new page with an incrementing counter. However, clicking the browser back button doesn't do what I want it to do. Let me explain the problem by breaking this post up into the following sections:
What I'd like to achieve
Undesired results in current project
Post all my code
1. What I'd like to achieve
I want the user to:
Open a new window and go to http://dktest.evermight.com/
Click next page and see a redbox fade in, and to see the url http://dktest.evermight.com/count.html?count=0 appear in both the iframe AND the browser's address bar
Click next page again and see http://dktest.evermight.com/count.html?count=1 in the iframe and browser's address bar
Click browser's back button ONCE and see http://dktest.evermight.com/count.html?count=0 in both the iframe and the browser's address bar
Click browser's back button ONCE and see http://dktest.evermight.com/ in the browser's address bar AND see the red box fade out
2. Undesired results in current project
With my code at http://dktest.evermight.com/, it's currently not performing steps 4 and steps 5 correctly. When I perform step 4, the iframe shows http://dktest.evermight.com/count.html?count=0 but the browser address bar shows http://dktest.evermight.com/count.html?count=1. I have to press the browser's back button again to make the browser address bar show http://dktest.evermight.com/count.html?count=0. When I perform step 5, the red box fades out which is great, but the address bar is still showing http://dktest.evermight.com/count.html?count=0. I have to press back again to make the address bar show http://dktest.evermight.com/.
3. Post all my code
My code is pretty straight forward. You can view source on http://dktest.evermight.com/. I will also post here for convenience.
index.html
<!DOCTYPE html>
<html>
<head>
<title></title>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript">
var count=0;
function clicknext()
{
$('#container').fadeIn();
$('#iframe').attr('src','count.html?count='+count.toString());
$('html title').html(count);
history.pushState({blahblah:'whatgoeshere?'},'i dont know what goes here either','http://dktest.evermight.com/count.html?count='+count);
count++;
}
function hideContainer()
{
$('#container').fadeOut();
var closeurl = 'close.html';
if($('#iframe').attr('src') != closeurl )
$('#iframe').attr('src', closeurl);
}
$(document).ready(function(){
hideContainer();
});
</script>
</head>
<body>
<div id="container" style="display:none; background:red;">
<!-- IMPORTANT
When DOM first created, the iframe.src MUST BE initialize.html
I have some code that I need to fire on that page before the rest
of this document starts
-->
<iframe id="iframe" src="initialize.html"></iframe>
</div>
<input type="button" onclick="clicknext()"; value="next page" />
</body>
</html>
close.html
<!DOCTYPE html>
<html>
<script type="text/javascript">
parent.hideContainer();
</script>
</html>
count.html
I CAN NOT modify the contents of count.html. In my real project, count.html is actually a youtube video, which is on a server I can't directly access.
<html>
<body>Youtube video at url <script type="text/javascript">document.write(location.href);</script></body>
</html>
initialize.html
Perform application specific functionality
Can anyone correct my code to achieve the results of step 4 and step 5 as described in section 1?
UPDATE
Ok, I'm appreciating the problem a bit more based on some experiments I'm doing.
Experiment 1: I tried changing the line:
$('#iframe').attr('src','count.html?count='+count.toString());
to
$('#iframe')[0].contentWindow.location.replace('count.html?count='+count.toString());
This allowed me to perform step 4 correctly. Apparently, contentWindow.location.replace() will not create an entry in the history object. However, this caused some other issues related with the contents of count.html, which is actually a page to youtube/vimeo content. The youtube/vimeo content REQUIRES that you load information via the attr('src') approach instead of .contentWindow.location.replace(). So perhaps the solution is to find a way to make attr('src') NOT create an entry with the history object?
Experiment 2 Another possible solution I tried was changing the order of the attr('src') and history.pushState() call. I tried calling attr('src') first then history.pushState() second, and also history.pushState() first then attr('src') second. But in both cases, when I push the browser's back button, it is the iframe content that goes back first. So there's no way for me to capture pass myself a message via the history object to do a "double back", since information in the history object is available LAST in the sequence of events.
Experiment 3 I also tried working with History.js. It did not do anything to solve my problems above. From what I could tell, it worked exactly like the regular history object.
Does anyone have any thing else I can try? Or suggest modifications to any of the experiments above? I'm going to explore Experiment 1 further as a separate stack overflow question.
I create a new iframe and destroy the iframe when loading new content. That solves the history issues.
I know this is a history problem but if you are still open to other possibilities, I think jquery-pjax is actually more suitable for what you are trying to do.
UPDATE I think this should work.
count.html
<div id="pjax-container">
<a id="pjax" data-pjax href="#">Next Page</a>
</div>
javascript
// get URL parameter (count): http://stackoverflow.com/questions/1403888/get-url-parameter-with-jquery
function getURLParameter(name) {
return decodeURI(
(RegExp(name + '=' + '(.+?)(&|$)').exec(location.search)||[,null])[1]
);
}
$(document).on('pjax:beforeSend', function() {
// your fading code goes here
})
$(document).on('pjax:complete', function() {
// fade out
// and then modify the anchor's href with something like
var new_count = getURLParameter('count') + 1;
$('a#pjax').attr('href', 'count.html?count=?' + new_count);
})
// where the pjaxed content should go
$(document).pjax('a[data-pjax]', '#pjax-container')
Related
On my site, Link A and Link B can link to Page X.
I want to start a video automatically on Page X if I come from Link A, but NOT when I come from Link B.
Is there any way I can do this using javascript/jquery?
For Reference: I am using fancy box to start the video.
There are two approaches you can take to this problem.
Option 1
This option was my first proof of concept.
On your first page:
Link A
Link B
And on /newpage:
<script type="text/javascript">
$(function(){
if(window.location.hash === "#linkA"){
// play video
}
});
</script>
or Option 2:
The first option doesn't account for the fact that the page will not refresh if you use the back button. Using a query string does cause the page to refresh though, thus breeding this solution.
On your first page:
Link A
Link B
And on /newpage:
<script type="text/javascript">
$(function(){
if(window.location.search.substring(1) === "playVideoA=1"){
// play video
}
});
</script>
So essentially you want to detect history. Simply use document.referrer.
Something like:
document.addEventListener("load", function() {
if (document.referrer === LINK_A) {
startVideo();
}
});
should be fine for your purposes.
I can think of two ways to do this. One is to check the value of document.referrer to see what the previous page was. A better way is to have your Page X accept a "autostart_video" HTTP GET parameter. So your link would go to a url like http://mysite.com/pageX?autostart=True . If your page is built dynamically (e.g. if you are using Django) then you can check for that parameter and modify the javsacript accordingly.
I have a site that uses AJAX to dynamically load content into a div.
The links to do so are anchors with href="#" and an onclick event to trigger the AJAX.
This leaves me without a history when I click back, so if I load one page, then another and click back, it does nothing.
A basic version of the code is this:
<script type="text/javascript">
function loadXMLDoc(url)
{
<!-- Load XML Script here. -->
}
</script>
</head>
<body>
<div id="myDiv">
<!-- Target div. -->
</div>
Click Me.
Click Me.
Click Me.
</body>
What I would like to know is, can I give each link a different "#" and then use a popstate handler to call the appropriate event, so if I click link 1, 2 and then 3 and then start hitting the back button, it'll go back to 2 and then 1 etc..
I was going to use history.js and start using pushstate in the loadXML script but I think the whole manipulating history thing is a bit dirty and unreliable.
Am I thinking on the right lines or is there a better way?
Currently all my links just use "#" so that it pops back to the top of the page when loading more content but I'd like to be able to go back if possible.
Any help would be great.
Browser saves hashtags to history properly. Just add hashtag #1 to this question page, hit enter, change it to #2, hit enter, change it to #3, hit enter. Now click back button, and you'll see hash changes from #3 to #2. I recommend to change only hash itself on link click and react on page hash change and page load events.
function react() {
var hash = window.location.hash.replace("#", "");
loadXMLDoc(hash + ".txt");
};
document.body.onload = function() {
react();
window.onhashchange = react;
};
Click me
Click me
Click me
Please note that onhashchange event does not supported by old IE. The only way to deal with it if you want is to define timer with setInterval and check hashes equality.
Try to use combination of LocalStorage and HistoryAPI.
When you load XMLDoc store it in LocatStorage, when back is pressed - load data from storage, not from web.
A bit code above.
/* Handling history.back added */
window.onpopstate = function(event) {
yourHandleBackFunction(event.state);
};
function yourHandleBackFunction(renderTs) {
/*Check TS and load from localStorage if needed*/
};
I'm trying to do something in Sharepoint 2010 that ought to be very simple, create a button that changes page (to a "create new item" form as it happens).
I set up a Content Editor Webpart and put a button in it (not in a form, because in Sharepoint the whole page is a form) with an "onclick" handler that changed the windows.location.href.
In 2010 the CEWP fights you a bit when you try to enter non-trivial HTML, it keeps escaping characters like "&" which can be a real pain. However in the end I got the right content entered.
It didn't work (the page just refreshed itself without changing URL). By checking on StackOverflow I found some recommendations for a more robust form for the CEWP content, which ended up as-
<script type="text/javascript">
function submit_rec(){
window.location.href = "<my server root URL>/Lists/Rec/NewForm.aspx";
return;
}
</script>
<button onclick="javascript:return submit_rec();return false"/>Submit a Recommendation</button>
Here's the strange part.
If I use Firebug and put a breakpoint in the submit_rec() function this works fine. But without a breakpoint, it goes back to the behaviour of always returning to the current page.
It seems there's a timing issue, or Sharepoint is taking control after my URL starts to load, and reloads the original page again!
Anyone seen this before and found a solution?
Ideas and suggestions woudl be much appreciated.
Regards: colin_e
Try this:
javascript:SP.UI.ModalDialog.OpenPopUpPage('/dev/KfD/KfDdev/Lists/Recommendation/NewForm.aspx');return false;
in the onclick event
Thanks to everyone who responded. With some more experimentation, and following hints from other threads on Stackoverflow, I was finally able to get this working.
My mistake with my last effort, using the Sharepoint builtin OpenNewFormUrl() function, was to expect this this would be a global function defined in a central library by SP. Turns out it's not, it has to be defined separately on every page where it's used, partly because it hard-codes the size of the popup frame for the library edit form.
(Yes this is ugly, like a lot of Sharepoint under the covers, anyway, I digress...)
I was able to get a Sharepoint 2010 style "popup" editor working with a button of the same style as the standard SP Document Centre "Submit a Document" button using the following code in a Content Editor WebPart. I have no idea what the script does in detail, I just copied it from the Document Centre site template home page-
<script type="text/javascript">
// <![CDATA[
function ULS18u(){var o=new Object;o.ULSTeamName="DLC Server";o.ULSFileName="default.aspx";return o;}
var navBarHelpOverrideKey = "wssmain";
// ]]>
function OpenNewFormUrl(url)
{ULS18u:;
var options = {width:640, height:720};
SP.UI.ModalDialog.commonModalDialogOpen(url, options, null, null);
}
</script>
<div class="ms-uploadbtnlink">
<button onclick="javascript:OpenNewFormUrl('/dev/KfD/KfDdev/Lists/Recommendation/NewForm.aspx');return false;" type="submit"><nobr><img alt="Submit a Recommendation" src="/_layouts/Images/uploaddoc.png"/> <span>Submit a Recommendation</span></nobr>
</button>
</div>
I'm wary of what setup this will do if (say) the users screen is smaller than the hard-coded popup size, and i'm still confused as to why my earlier (and much simpler) efforts failed, but at least I have a working soluion.
I found this nice jQuery preloader/progress bar, but I cannot get it to work as it is supposed to. The problem is that it first loads my page and after my whole page is loaded the 0%-100% bar displays quickly, after that it reloads my page again. So it does not show the progress bar BEFORE the page loads and it loads the page a second time as well.
Here is my implementation code:
<head>
<script src="js/jquery-1.7.2.min.js" type="text/javascript"></script>
<script src="js/jquery.queryloader2.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
$("body").queryLoader2();
});
</script>
</head>
<body>
My content...No other reference in here for the Jquery preloader
</body>
Thanks for any help in advance.
I could be very, very wrong here, but in my opinion:
The plugin is flawed.
You have some issue in your page that causes a redirect.
I have created a test fiddle and found out the following:
If there are no images on the page, then the plugin's private function completeImageLoading(); is never called because it is only bound to the image elements. When there are no images -> there's no binding -> no triggering -> nothing completes -> you stay with overlay 0% as demonstrated by the fiddle that is NOT RUN (jsfiddle doesn't see relative images when the page is not run).
The plugin doesn't take into consideration remote images. So if you declare them like so <img src="http://example.com/image.jpg"> - then it won't work because the plugin doesn't recognize them. In fact it is using $.ajax to load images which, obviously, generates a error when trying to access another domain.
The plugin doesn't reload the page (at least in Google Chrome)... check your console output while in the fiddle. It displays the message once per click on Run.
Suggestions:
Make sure you provide at least one relative or background image (though I haven't tested backgrounds...) for the plugin to work.
Show us more code. The fiddle demonstrates that the plugin does NOT cause page reload (at least in Chrome... are you using another browser?). It must be something you made that interferes here.
Specify some options for the plugin (behaves weird when there are none).
Edit regarding preloader
Regarding preloader... if displaying progress is not mandatory for you, then you can just use a window.onload trick. On DOM ready $(...) you create an opaque page overlay with a "Please wait..." message and some animation if you fancy it. Then you wait for window.onload event which "fires at the end of the document loading process... when all of the objects in the document are in the DOM, and all the images and sub-frames have finished loading." When window.onload triggers, you just remove your overlay and voila - the page is ready!
Edit 2 regarding preloader
Actually, you don't even need $(...)... what the hell was I thinking? Just create your overlay (a simple div with a unique id) in your html, style it so that it fills the screen and give it a z-index:1337 CSS attribute so that it covers the entire page. Then, on window.onload:
window.onload = function () {
// Grab a reference to your overlay element:
var overlay = document.getElementById('myOverlay');
// Check if the overlay really exists
// and if it is really appended to the DOM,
// because if not - removeChild throws an error
if (overlay && overlay.parentNode && overlay.parentNode.nodeType === 1) {
// Remove overlay from DOM:
overlay.parentNode.removeChild(overlay);
// Now trash it to free some resources:
overlay = null;
}
};
Of course, it's not really a preloader, but simply an imitation.
Here's a working fiddle you can play with.
P.S. I personally don't appreciate preloaders, but that's just me...
Try out this(Remove the document.ready event and simply call this):-
<script type="text/javascript">
$("body").queryLoader2();
</script>
My LogIn action originally looked like this:
return new RedirectResult(nameValueCollection["ReturnUrl"]);
But, I would like to know whether the client has JavaScript enabled before the home page loads, so I changed it to this:
return View(new LogInViewModel { ReturnUrl = nameValueCollection["ReturnUrl"] });
And send the following view instead of the instant-redirect:
#model Obr.Web.Models.LogInViewModel
#{
Layout = null;
string noJSReturnUrl = Model.ReturnUrl + (Model.ReturnUrl.Contains("?") ? "&" : "?") + "noJS=true";
}
<!doctype html>
<html>
<head>
<title>Loggin in...</title>
<meta http-equiv="REFRESH" content="1;url=#noJSReturnUrl">
<script type="text/javascript">
window.location = "#Model.ReturnUrl";
</script>
</head>
<body>
<noscript>
Loggin in...<br />
Click here if you are not redirected promptly.
</noscript>
</body>
</html>
The idea is that if the user does not have JavaScript enabled, they see a brief loading message, and the home page loads after a second. If JavaScript is enabled, the page reloads instantly. In the future I could even post to the server the dimensions of the viewport and such.
Does this look like it would work? If the window.location command takes longer than a second to run, will it be interrupted by the meta refresh, or does it block that refresh? I am hoping the latter, so I don't need to increase the delay for those non-js people.
I figure my new way adds a little extra weight to the payload of the redirect, but it's not an extra round-trip or anything, is it? The redirect happens anyway, does it not?
Update: I neglected to mention a very important point. I do not actually have control over the login screen itself, only the page it posts to. This code is part of a product that relies on an external authentication mechanism.
You do not need the extra redirect just to detect javascript. On the original form where the user logs in, create a hidden form element javaScriptEnabled with a default value of false. Then use JavaScript to set the value to true. Then you can read this value in the handler. If it's true, then JS is enabled.
No extra page needed.
Since you can't change the original login form then your solution looks good. It won't display anything to the user who has JS and should look just like another redirect, with just an extra hop.
Once you write a new url to window.location then the browser will stop processing the current page's js and timers and everything and simply move on to retrieving/processing the next page.