Change page without reloading header/footer? - javascript

I've seen a lot of sites recently that allow you to navigate to different pages (seemingly) without reloading the page. For example:
https://www.protest.eu/shop/category/men/
I know I can do it via AJAX by just replacing the content and changing the url, but that has drawbacks. Mainly, if you're trying to track page visits, they won't show up for pages that are navigated to in this way... because you're not actually visiting the page.
Is there a better way to achieve this?

I know I can do it via AJAX
That's how you do it.
if you're trying to track page visits, they won't show up for pages that are navigated to in this way
How you fix that depends on what you are using to track page visits.
If, for example, you were using Google Analytics then you would do something like:
function ajaxLoadHandler() {
var content = this.responseText;
var url = "/bar.html";
update_content_with(content);
history.pushState({ raw_content: content }, "page 2", url);
ga('send', {
hitType: 'pageview',
page: url
});
}

This approach is called as SPA (single page application). The dowbacks you mentioned earlier can handled by some Js methods and event listener(histrory.pushstate, onpopstate... ref:https://developer.mozilla.org/en-US/docs/Web/API/WindowEventHandlers/onpopstate.)
Some of JS framework s (like React,Backbone,CanJS,SpineJS,BatmanJS,EmberJS,AngularJS, etc) help to achive SPA sloution. These framework provides routing module to achive browser history functionality also these provides view, model, controller, collection WTC.,. You may choose one of these framework which suits for your business need.

Related

How to achieve authorization ? How to prevent a user from directly accessing my html pages by writing URL?

I'm working on a node-red project with uibuilder node.
It's basically [html, css, js(with vue)] pages.
I want to make the login authorization part where each user opens the allowed pages only.
How can I achieve that? by tokens? by permitting direct access to pages using URL?
P.S. I'm new to this part of web and I tried searching but couldn't find what I need.
I searched a lot, all was dead-end until I found this question
Detect if page was redirected or loaded directly(Javascript)
Instead of getting into trouble with tokens, and checking at each page if it is valid or not.
I permitted accessing any page (except the login) by the URL. If you want to access a page, it's only by redirecting.
I achieved that by checking a variable at page loading if the page has history or not. if no history, it is redirected to the login page.
I added this part to my vue-js file:
window.onload = function() {
if(document.referrer == "") window.location.href = "http://localhost:1880/Login/login.html";
}
P.S. If all the Internet said preventing accessing by URL is impossible, Don't be disappointed. Search more, because it's actually possible. 😉 😉

Alert box after redirect

so i know this may sound stupid, but I want to know if there is any way that i could redirect someone to a website, and then display an alert box on the web page, using either javascript or any other interface that can be weaved into HTML5. I asked some of my classmates, and they didn't know, so I just need a confirmation that this isn't possible.
I have ran a few trials i found, but on further review, they wouldn't work.
edit I have control over the site, but I wish for the box to only pop up if i redirect it.
I can give the code if it would help, but I'm doubtful it will help
sorry for wasting your time if i did. thanks.
Similar to Gerard's answer, but using query strings. A possibly more standard solution.
On the first page:
<script>
window.location = 'https://{your website here}/?showAlert=true';
</script>
Then on the 2nd page.
const urlParams = new URLSearchParams(window.location.search);
const showAlert = urlParams.get('showAlert');
if(showAlert === "true") {
alert("Hello");
}
Note this will not work in internet explorer
You could communicate to the new site that it's a redirect by appending the route:
On the site you want to redirect from:
<script>
// if you can't use a normal link, change the url with JS
window.location = 'https://{your website here}/#redirect';
</script>
On the site you want to show the alert:
<script>
if (window.location.pathname.includes('#redirect') alert('What you want to say');
</script>
If you only have control over the first site, you could alert before redirecting, there wouldn't be much difference to the user since the alert blocks execution of other code.
You can call an alert box in a HTML document with JavaScript like this:
window.onload = function () {
alert("Hello World!");
}
-> https://jsfiddle.net/u8x6s31v/
You can also redirect somebody, if the page he's visiting is yours. Is that what you mean?
Update:
I think you can't see the URL where someone comes from with JavaScript. The only way to trigger scripts for some people is to add a hash.
window.onload = function () {
hashUrl = window.location.hash;
if (hashUrl == "#alert") {
alert("Hello World!");
}
}
Then call for example: domain.tld/path/index.html#alert
-> https://jsfiddle.net/u8x6s31v/1/
This is a vague questions with a lot of possible answers but seeing as how you're new, I'm going to speculate on what you might be asking and try to answer it.
It's not clear what you mean by "redirect".
Is this a server-side redirect like when you move/change a URL and you redirect the old URL to a new URL? Is this a Javascript meta refresh that you put in a 404 template? Is this a redirect that occurs after a user takes an action?
Regardless, you're going to have to "annotate" that user and then take action upon that annotation. The most obvious method would be based on the "referrer" HTTP header but it is also possible to do it based on the presence of a cookie.
Additionally, adding URL parameters to a redirect is trivially easy and often used for stuff like this.
The immediate things that come to my mind would be via Google Analytics (preferably implemented via Google Tag Manager because it'll make it easier).
Look into "outbound link tracking", "cross-domain tracking" and "UTM campaign tracking" (all related to Google Analytics and/or Google Tag Manager) and you'll probably find something that suits your needs.
URL shorteners are commonly used to mask parameters in links and there are open source libraries that allow you to host your own URL shortener (which you could integrate into your redirects) or do some other type of link tracking like is often used for affiliates.

forcing page load on an AJAX-loaded page

I have an issue with an third-party integration on an iPad-specific website, which has a number of pages loaded via AJAX.
When I go to the page for the first time the functionality that is expected to be available is not, and only when I do a page refresh in Safari do I see the feature.
In the 3rd party JavaScript there is this sort of code peppered throughout:
script.onload = script.onreadystatechange = function () { // do something }
Here is the full JavaScript included file.
Is there a way that I can either force a page load on the iPad or build in some workaround that means that when I change to the page where the JavaScript is included and fires?
As I mentioned, this is only apparent on an iPad-specific website and the same feature has no problem on a desktop browser where the page is not loaded via AJAX.
i believe web servers allow you to add content dynamically for all pages rendered using the web server. which allows you to insert a code snippet which can ideally check if its a ipad website and do page load as you requested.
follow the below thread
http://www.microsoft.com/technet/prodtechnol/WindowsServer2003/Library/IIS/e27f918e-89a9-45a8-8604-2ad2ded09d64.mspx?mfr=true
I have no idea what your code looks like, but, having experienced the same issues repeatedly with jQuery, I would suggest you manually call the initialize function of the 3rd party script within a window ready state function:
$(window).ready(function(e) {
// function that initializes the 3rd party script gets called here.
});

How to parse a web use javascript to load .html by Python?

I'm using Python to parse an auction site.
If I use browser to open this site, it will go to a loading page, then jump to the search result page automatically.
If I use urllib2 to open the webpage, the read() method only return the loading page.
Is there any python package could wait until all contents are loaded then read() method return all results?
Thanks.
How does the search page work? If it loads anything using Ajax, you could do some basic reverse engineering and find the URLs involved using Firebug's Net panel or Wireshark and then use urllib2 to load those.
If it's more complicated than that, you could simulate the actions JS performs manually without loading and interpreting JavaScript. It all depends on how the search page works.
Lastly, I know there are ways to run scripting on pages without a browser, since that's what some functional testing suites do, but my guess is that this could be the most complicated approach.
After tracing for the auction web source code, I found that it uses .php to create loading page and redirect to result page. Reverse engineering to find the ture URLs is not working because it's the same URL as loading page.
And #Manoj Govindan, I've tried Mechanize, but even if I add
br.set_handle_refresh(True)
br.set_handle_redirect(True)
it still read the loading page.
After hours of searching on www, I found a possible solution : using pywin32
import win32com.client
import time
url = 'http://search.ruten.com.tw/search/s000.php?searchfrom=headbar&k=halo+reach'
ie = win32com.client.Dispatch("InternetExplorer.Application")
ie.Visible = 0
ie.Navigate(url)
while 1:
state = ie.ReadyState
if state == 4:
break
time.sleep(1)
print ie.Document.body.innerHTML
However this only works on win32 platform, I'm looking for a cross platform solutoin.
If anyone know how to deal this, please tell me.

ajax based webpage - good way to do it?

I build a website focussing on loading only data that has to be loaded.
I've build an example here and would like to know if this is a good way to build a wegpage.
There are some problems when building a site like that, e.g.
bookmarking
going back and forth in
history SEO (since the content is basically not really connected)
so here is the example:
index.html
<html>
<head>
<title>Somebodys Website</title>
<!-- JavaScript -->
<script type="text/javascript" src="jquery-1.3.2.min.js"></script>
<script type="text/javascript" src="pagecode.js"></script>
</head>
<body>
<div id="navigation">
<ul>
<li>Welcome</li>
<li>Page1</li>
</ul>
</div>
<div id="content">
</div>
</body>
</html>
pagecode.js
var http = null;
$(document).ready(function()
{
// create XMLHttpRequest
try {
http = new XMLHttpRequest();
}
catch(e){
try{
http = new ActiveXObject("MS2XML.XMLHTTP");
}
catch(e){
http = new ActiveXObject("Microsoft.XMLHTTP");
}
}
// set navigation click events
$('.nav').click(function(e)
{
loadPage(e);
});
});
function loadPage(e){
// e.g. "link_Welcome" becomes "Welcome.html"
var page = e.currentTarget.id.slice(5) + ".html";
http.open("POST", page);
http.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
http.setRequestHeader("Connection", "close");
http.onreadystatechange = function(){changeContent(e);};
http.send(null);
}
function changeContent(e){
if(http.readyState == 4){
// load page
var response = http.responseText;
$('#content')[0].innerHTML = response;
}
}
Welcome.html
<b>Welcome</b>
<br />
To this website....
So as you can see, I'm loading the content based on the IDs of the links in the navigation section. So to make the "Page1" navigation item linkable, i would have to create a "Page1.html" file with some content in it.
Is this way of loading data for your web page very wrong? and if so, what is a better way to do it?
thanks for your time
EDIT:
this was just a very short example and i'd like to say that for users with javascript disabled it is still possible to provide the whole page (additionally) in static form.
e.g.
<li>Welcome</li>
and this Welcome.html would contain all the overhead of the basic index.html file.
By doing so, the ajax using version of the page would be some kind of extra feature, wouldn't it?
No, it isn't a good way to do it.
Ajax is a tool best used with a light touch.
Reinventing frames using it simply recreates all the problems of frames except that it replaces the issue of orphan pages with complete invisibility to search engines (and other use agents that don't support JS or have it disabled).
By doing so, the ajax using version of the page would be some kind of extra feature, wouldn't it?
No. Users won't notice, and you break bookmarking, linksharing, etc.
It's wrong to use AJAX (or any javascript for that matter) only to use it (unless you're learning how to use ajax which is diffrent matter).
There are situations where the use of javascript is good (mostly when you're building a custom user interface inside your browser window) and when AJAX really shines. But loading static web pages with javascript is very wrong: first, you tie yourself with a browser that can run your JS, second you increase the load on your server and on the client side.
More technical details:
The function loadPage should be re-written using jquery : $post(). This is a random shot, not tested:
function loadPage(e){
// e.g. "link_Welcome" becomes "Welcome.html"
var page = e.currentTarget.id.slice(5) + ".html";
$.post( page, null, function(response){
$('#content')[0].innerHTML = response;
} );
}
Be warned, I did not test it, and I might get this function a little wrong. But... dud, you are using jQuery already - now abuse it! :)
When considering implementing an AJAX pattern on a website you should first ask yourself the question: why? There are several good reasons to implement AJAX but also several bad reasons depending on what you're trying to achieve.
For example, if your website is like Facebook, where you want to offer end-users with a rich user interface where you can immediately see responses from friends in chat, notifications when users post something to your wall or tag you in a photo, without having to refresh the entire page, AJAX is GREAT!
However, if you are creating a website where the main content area changes for each of the top-level menu items using AJAX, this is a bad idea for several reasons: First, and what I consider to be very important, SEO (Search Engine Optimization) is
NOT optimized. Search engine
crawlers do not follow AJAX requests
unless they are loaded via the
onclick event of an anchor tag.
Ultimately, in this example, you are
not getting the value out of the rich
experience, and you are losing a lot
of potential viewers.
Second, users will have trouble bookmarking pages unless you implement a smart way to parse URLs to map to AJAX calls.
Third, users will have problems properly navigating using the back and forward buttons if you have not implemented a custom client-side mechanism to manage history.
Lastly, each browser interprets JavaScript differently, and with the more JavaScript you write, the more potential there is for losing cross browser compatibility unless you implement a framework that such as jQuery, Dojo, EXT, or MooTools that handles most of that for you.
gabtub you are not wrong, you can get working AJAX intensive web sites SEO compatible, with bookmarking, Back/Forward buttons (history navigation in general), working with JavaScript disabled (avoiding site duplication), accessible...
There is one problem, you must get back to server-centric.
You can get some "howtos" here.
And take a look to ItsNat.
How about unobtrusivity (or how should I call it?)?
If the user has no javascript for some reason, he'll only see a list with Welcome and Page1.
Yes it's wrong. What about users without JavaScript? Why not do this sort of work server-side? Why pay the cost of multiple HTTP requests instead of including the files server-side so they can be downloaded in a single fetch? Why pay the cost of non-JavaScript enabled clients not being able to view your stuff (Google's spider being an important user who'll be alienated by this approach)? Why? Why?

Categories

Resources