Creating two html pages in SAPUI5 and executing one or the other depends on the situation - html

Currently I have my project running as welcomFile the index.html file. This file takes me to an authentication process. The case is that I need to access one of my views but without performing this authentication, that is, I don't want to go through this index.html. To do so, I created another html (index_new.html). Even if I run this last one it always redirects me to the index.html, I don't know if it has to do with how the neo-app.json file is configured. I tried to put in the index.html that if it arrived a parameter in the url to be directed to the index_new.html but without success, it says that the page does not exist. This is what I tried:
<script>
const queryString = window.location.search;
const urlParams = new URLSearchParams(queryString);
window.location.search = urlParams.toString();
const con = urlParams.get('con');
if (con !== ""){
window.open("/index_new.html", "_self");
}
</script>
The only way I have managed to load the path I want is to run the program, it goes to the index.html and once it has loaded, I change the path to the index_new.html/viewthatIwanttoshow and it shows up. Is there any way to run the new index_new.html without having to run the old one?
I also think it's because of the manifest, because from the index_new.html I do it like this, just like in the index.html:
……
<script id="sap-ui-bootstrap>
…
data-sap-ui-resourceroots='{"app.hello”: “./“}’
…
</script>
</head>
<body class="sapUiBody">
<div data-sap-ui-component data-name="app.hello” data-id="container" data-settings='{"id" : “hello”}’ style="height: 100%"></div>
</body>
Maybe I should change the path here but I don't know which one or how to configure it in the manifest.json.
Maybe my question is not clear, if you have any questions please let me know.
My neo-app.json:
"welcomeFile": "/webapp/index.html",
My manifest.json:
"sap.app": {
"id": “app.hello”,
"type": "application",

I can't / don't want to give you a direct answer on your question. But I would like to mention to think about the concept you are going for.
I don't really understand why you want to load different index.html files. It's pretty far away from a best practice scenario - at least with the information I have out of your post.
When we are talking about authentication, mostly you save a token in cookies / browser storage. Then you can check if you are authenticated. If so, use the UI5 router. In every page you want to, you can check for valid authentication / authorization and redirect again to a login page, if you are not.
IMO you shouldn't use two different index.html sites.
I hope this help you to find another way to solve it.

Related

How can i add a link to a button? [duplicate]

This question's answers are a community effort. Edit existing answers to improve this post. It is not currently accepting new answers or interactions.
How can I redirect the user from one page to another using jQuery or pure JavaScript?
One does not simply redirect using jQuery
jQuery is not necessary, and window.location.replace(...) will best simulate an HTTP redirect.
window.location.replace(...) is better than using window.location.href, because replace() does not keep the originating page in the session history, meaning the user won't get stuck in a never-ending back-button fiasco.
If you want to simulate someone clicking on a link, use
location.href
If you want to simulate an HTTP redirect, use location.replace
For example:
// similar behavior as an HTTP redirect
window.location.replace("http://stackoverflow.com");
// similar behavior as clicking on a link
window.location.href = "http://stackoverflow.com";
WARNING: This answer has merely been provided as a possible solution; it is obviously not the best solution, as it requires jQuery. Instead, prefer the pure JavaScript solution.
$(location).prop('href', 'http://stackoverflow.com')
Standard "vanilla" JavaScript way to redirect a page
window.location.href = 'newPage.html';
Or more simply: (since window is Global)
location.href = 'newPage.html';
If you are here because you are losing HTTP_REFERER when redirecting, keep reading:
(Otherwise ignore this last part)
The following section is for those using HTTP_REFERER as one of many security measures (although it isn't a great protective measure). If you're using Internet Explorer 8 or lower, these variables get lost when using any form of JavaScript page redirection (location.href, etc.).
Below we are going to implement an alternative for IE8 & lower so that we don't lose HTTP_REFERER. Otherwise, you can almost always simply use window.location.href.
Testing against HTTP_REFERER (URL pasting, session, etc.) can help tell whether a request is legitimate.
(Note: there are also ways to work-around / spoof these referrers, as noted by droop's link in the comments)
Simple cross-browser testing solution (fallback to window.location.href for Internet Explorer 9+ and all other browsers)
Usage: redirect('anotherpage.aspx');
function redirect (url) {
var ua = navigator.userAgent.toLowerCase(),
isIE = ua.indexOf('msie') !== -1,
version = parseInt(ua.substr(4, 2), 10);
// Internet Explorer 8 and lower
if (isIE && version < 9) {
var link = document.createElement('a');
link.href = url;
document.body.appendChild(link);
link.click();
}
// All other browsers can use the standard window.location.href (they don't lose HTTP_REFERER like Internet Explorer 8 & lower does)
else {
window.location.href = url;
}
}
There are lots of ways of doing this.
// window.location
window.location.replace('http://www.example.com')
window.location.assign('http://www.example.com')
window.location.href = 'http://www.example.com'
document.location.href = '/path'
// window.history
window.history.back()
window.history.go(-1)
// window.navigate; ONLY for old versions of Internet Explorer
window.navigate('top.jsp')
// Probably no bueno
self.location = 'http://www.example.com';
top.location = 'http://www.example.com';
// jQuery
$(location).attr('href','http://www.example.com')
$(window).attr('location','http://www.example.com')
$(location).prop('href', 'http://www.example.com')
This works for every browser:
window.location.href = 'your_url';
It would help if you were a little more descriptive in what you are trying to do. If you are trying to generate paged data, there are some options in how you do this. You can generate separate links for each page that you want to be able to get directly to.
<a href='/path-to-page?page=1' class='pager-link'>1</a>
<a href='/path-to-page?page=2' class='pager-link'>2</a>
<span class='pager-link current-page'>3</a>
...
Note that the current page in the example is handled differently in the code and with CSS.
If you want the paged data to be changed via AJAX, this is where jQuery would come in. What you would do is add a click handler to each of the anchor tags corresponding to a different page. This click handler would invoke some jQuery code that goes and fetches the next page via AJAX and updates the table with the new data. The example below assumes that you have a web service that returns the new page data.
$(document).ready( function() {
$('a.pager-link').click( function() {
var page = $(this).attr('href').split(/\?/)[1];
$.ajax({
type: 'POST',
url: '/path-to-service',
data: page,
success: function(content) {
$('#myTable').html(content); // replace
}
});
return false; // to stop link
});
});
I also think that location.replace(URL) is the best way, but if you want to notify the search engines about your redirection (they don't analyze JavaScript code to see the redirection) you should add the rel="canonical" meta tag to your website.
Adding a noscript section with a HTML refresh meta tag in it, is also a good solution. I suggest you to use this JavaScript redirection tool to create redirections. It also has Internet Explorer support to pass the HTTP referrer.
Sample code without delay looks like this:
<!-- Place this snippet right after opening the head tag to make it work properly -->
<!-- This code is licensed under GNU GPL v3 -->
<!-- You are allowed to freely copy, distribute and use this code, but removing author credit is strictly prohibited -->
<!-- Generated by http://insider.zone/tools/client-side-url-redirect-generator/ -->
<!-- REDIRECTING STARTS -->
<link rel="canonical" href="https://yourdomain.example/"/>
<noscript>
<meta http-equiv="refresh" content="0;URL=https://yourdomain.example/">
</noscript>
<!--[if lt IE 9]><script type="text/javascript">var IE_fix=true;</script><![endif]-->
<script type="text/javascript">
var url = "https://yourdomain.example/";
if(typeof IE_fix != "undefined") // IE8 and lower fix to pass the http referer
{
document.write("redirecting..."); // Don't remove this line or appendChild() will fail because it is called before document.onload to make the redirect as fast as possible. Nobody will see this text, it is only a tech fix.
var referLink = document.createElement("a");
referLink.href = url;
document.body.appendChild(referLink);
referLink.click();
}
else { window.location.replace(url); } // All other browsers
</script>
<!-- Credit goes to http://insider.zone/ -->
<!-- REDIRECTING ENDS -->
But if someone wants to redirect back to home page then he may use the following snippet.
window.location = window.location.host
It would be helpful if you have three different environments as development, staging, and production.
You can explore this window or window.location object by just putting these words in Chrome Console or Firebug's Console.
JavaScript provides you many methods to retrieve and change the current URL which is displayed in browser's address bar. All these methods uses the Location object, which is a property of the Window object. You can create a new Location object that has the current URL as follows..
var currentLocation = window.location;
Basic Structure of a URL
<protocol>//<hostname>:<port>/<pathname><search><hash>
Protocol -- Specifies the protocol name be used to access the resource on the Internet. (HTTP (without SSL) or HTTPS (with SSL))
hostname -- Host name specifies the host that owns the resource. For example, www.stackoverflow.com. A server provides services using the name of the host.
port -- A port number used to recognize a specific process to which an Internet or other network message is to be forwarded when it arrives at a server.
pathname -- The path gives info about the specific resource within the host that the Web client wants to access. For example, stackoverflow.com/index.html.
query -- A query string follows the path component, and provides a string of information that the resource can utilize for some purpose (for example, as parameters for a search or as data to be processed).
hash -- The anchor portion of a URL, includes the hash sign (#).
With these Location object properties you can access all of these URL components
hash -Sets or returns the anchor portion of a URL.
host -Sets
or returns the hostname and port of a URL.
hostname -Sets or
returns the hostname of a URL.
href -Sets or returns the entire
URL.
pathname -Sets or returns the path name of a URL.
port -Sets or returns the port number the server uses for a URL.
protocol -Sets or returns the protocol of a URL.
search -Sets
or returns the query portion of a URL
Now If you want to change a page or redirect the user to some other page you can use the href property of the Location object like this
You can use the href property of the Location object.
window.location.href = "http://www.stackoverflow.com";
Location Object also have these three methods
assign() -- Loads a new document.
reload() -- Reloads the current document.
replace() -- Replaces the current document with a new one
You can use assign() and replace methods also to redirect to other pages like these
location.assign("http://www.stackoverflow.com");
location.replace("http://www.stackoverflow.com");
How assign() and replace() differs -- The difference between replace() method and assign() method(), is that replace() removes the URL of the current document from the document history, means it is not possible to use the "back" button to navigate back to the original document. So Use the assign() method if you want to load a new document, andwant to give the option to navigate back to the original document.
You can change the location object href property using jQuery also like this
$(location).attr('href',url);
And hence you can redirect the user to some other url.
Basically jQuery is just a JavaScript framework and for doing some of the things like redirection in this case, you can just use pure JavaScript, so in that case you have 3 options using vanilla JavaScript:
1) Using location replace, this will replace the current history of the page, means that it is not possible to use the back button to go back to the original page.
window.location.replace("http://stackoverflow.com");
2) Using location assign, this will keep the history for you and with using back button, you can go back to the original page:
window.location.assign("http://stackoverflow.com");
3) I recommend using one of those previous ways, but this could be the third option using pure JavaScript:
window.location.href="http://stackoverflow.com";
You can also write a function in jQuery to handle it, but not recommended as it's only one line pure JavaScript function, also you can use all of above functions without window if you are already in the window scope, for example window.location.replace("http://stackoverflow.com"); could be location.replace("http://stackoverflow.com");
Also I show them all on the image below:
Should just be able to set using window.location.
Example:
window.location = "https://stackoverflow.com/";
Here is a past post on the subject: How do I redirect to another webpage?
Before I start, jQuery is a JavaScript library used for DOM manipulation. So you should not be using jQuery for a page redirect.
A quote from Jquery.com:
While jQuery might run without major issues in older browser versions,
we do not actively test jQuery in them and generally do not fix bugs
that may appear in them.
It was found here:
https://jquery.com/browser-support/
So jQuery is not an end-all and be-all solution for backwards compatibility.
The following solution using raw JavaScript works in all browsers and have been standard for a long time so you don't need any libraries for cross browser support.
This page will redirect to Google after 3000 milliseconds
<!DOCTYPE html>
<html>
<head>
<title>example</title>
</head>
<body>
<p>You will be redirected to google shortly.</p>
<script>
setTimeout(function(){
window.location.href="http://www.google.com"; // The URL that will be redirected too.
}, 3000); // The bigger the number the longer the delay.
</script>
</body>
</html>
Different options are as follows:
window.location.href="url"; // Simulates normal navigation to a new page
window.location.replace("url"); // Removes current URL from history and replaces it with a new URL
window.location.assign("url"); // Adds new URL to the history stack and redirects to the new URL
window.history.back(); // Simulates a back button click
window.history.go(-1); // Simulates a back button click
window.history.back(-1); // Simulates a back button click
window.navigate("page.html"); // Same as window.location="url"
When using replace, the back button will not go back to the redirect page, as if it was never in the history. If you want the user to be able to go back to the redirect page then use window.location.href or window.location.assign. If you do use an option that lets the user go back to the redirect page, remember that when you enter the redirect page it will redirect you back. So put that into consideration when picking an option for your redirect. Under conditions where the page is only redirecting when an action is done by the user then having the page in the back button history will be okay. But if the page auto redirects then you should use replace so that the user can use the back button without getting forced back to the page the redirect sends.
You can also use meta data to run a page redirect as followed.
META Refresh
<meta http-equiv="refresh" content="0;url=http://evil.example/" />
META Location
<meta http-equiv="location" content="URL=http://evil.example" />
BASE Hijacking
<base href="http://evil.example/" />
Many more methods to redirect your unsuspecting client to a page they may not wish to go can be found on this page (not one of them is reliant on jQuery):
https://code.google.com/p/html5security/wiki/RedirectionMethods
I would also like to point out, people don't like to be randomly redirected. Only redirect people when absolutely needed. If you start redirecting people randomly they will never go to your site again.
The next paragraph is hypothetical:
You also may get reported as a malicious site. If that happens then when people click on a link to your site the users browser may warn them that your site is malicious. What may also happen is search engines may start dropping your rating if people are reporting a bad experience on your site.
Please review Google Webmaster Guidelines about redirects:
https://support.google.com/webmasters/answer/2721217?hl=en&ref_topic=6001971
Here is a fun little page that kicks you out of the page.
<!DOCTYPE html>
<html>
<head>
<title>Go Away</title>
</head>
<body>
<h1>Go Away</h1>
<script>
setTimeout(function(){
window.history.back();
}, 3000);
</script>
</body>
</html>
If you combine the two page examples together you would have an infant loop of rerouting that will guarantee that your user will never want to use your site ever again.
var url = 'asdf.html';
window.location.href = url;
You can do that without jQuery as:
window.location = "http://yourdomain.com";
And if you want only jQuery then you can do it like:
$jq(window).attr("location","http://yourdomain.com");
This works with jQuery:
$(window).attr("location", "http://google.fr");
# HTML Page Redirect Using jQuery/JavaScript Method
Try this example code:
function YourJavaScriptFunction()
{
var i = $('#login').val();
if (i == 'login')
window.location = "Login.php";
else
window.location = "Logout.php";
}
If you want to give a complete URL as window.location = "www.google.co.in";.
Original question: "How to redirect using jQuery?", hence the answer implements jQuery >> Complimentary usage case.
To just redirect to a page with JavaScript:
window.location.href = "/contact/";
Or if you need a delay:
setTimeout(function () {
window.location.href = "/contact/";
}, 2000); // Time in milliseconds
jQuery allows you to select elements from a web page with ease. You can find anything you want on a page and then use jQuery to add special effects, react to user actions, or show and hide content inside or outside the element you have selected. All these tasks start with knowing how to select an element or an event.
$('a,img').on('click',function(e){
e.preventDefault();
$(this).animate({
opacity: 0 //Put some CSS animation here
}, 500);
setTimeout(function(){
// OK, finished jQuery staff, let's go redirect
window.location.href = "/contact/";
},500);
});
Imagine someone wrote a script/plugin with 10000 lines of code. With jQuery you can connect to this code with just a line or two.
So, the question is how to make a redirect page, and not how to redirect to a website?
You only need to use JavaScript for this. Here is some tiny code that will create a dynamic redirect page.
<script>
var url = window.location.search.split('url=')[1]; // Get the URL after ?url=
if( url ) window.location.replace(url);
</script>
So say you just put this snippet into a redirect/index.html file on your website you can use it like so.
http://www.mywebsite.com/redirect?url=http://stackoverflow.com
And if you go to that link it will automatically redirect you to stackoverflow.com.
Link to Documentation
And that's how you make a Simple redirect page with JavaScript
Edit:
There is also one thing to note. I have added window.location.replace in my code because I think it suits a redirect page, but, you must know that when using window.location.replace and you get redirected, when you press the back button in your browser it will not got back to the redirect page, and it will go back to the page before it, take a look at this little demo thing.
Example:
The process: store home => redirect page to google => google
When at google: google => back button in browser => store home
So, if this suits your needs then everything should be fine. If you want to include the redirect page in the browser history replace this
if( url ) window.location.replace(url);
with
if( url ) window.location.href = url;
You need to put this line in your code:
$(location).attr("href","http://stackoverflow.com");
If you don't have jQuery, go with JavaScript:
window.location.replace("http://stackoverflow.com");
window.location.href("http://stackoverflow.com");
On your click function, just add:
window.location.href = "The URL where you want to redirect";
$('#id').click(function(){
window.location.href = "http://www.google.com";
});
Try this:
location.assign("http://www.google.com");
Code snippet of example.
jQuery is not needed. You can do this:
window.open("URL","_self","","")
It is that easy!
The best way to initiate an HTTP request is with document.loacation.href.replace('URL').
Using JavaScript:
Method 1:
window.location.href="http://google.com";
Method 2:
window.location.replace("http://google.com");
Using jQuery:
Method 1: $(location)
$(location).attr('href', 'http://google.com');
Method 2: Reusable Function
jQuery.fn.redirectTo = function(url){
window.location.href = url;
}
jQuery(window).redirectTo("http://google.com");
First write properly. You want to navigate within an application for another link from your application for another link. Here is the code:
window.location.href = "http://www.google.com";
And if you want to navigate pages within your application then I also have code, if you want.
You can redirect in jQuery like this:
$(location).attr('href', 'http://yourPage.com/');
JavaScript is very extensive. If you want to jump to another page you have three options.
window.location.href='otherpage.com';
window.location.assign('otherpage.com');
//and...
window.location.replace('otherpage.com');
As you want to move to another page, you can use any from these if this is your requirement.
However all three options are limited to different situations. Chose wisely according to your requirement.
If you are interested in more knowledge about the concept, you can go through further.
window.location.href; // Returns the href (URL) of the current page
window.location.hostname; // Returns the domain name of the web host
window.location.pathname; // Returns the path and filename of the current page
window.location.protocol; // Returns the web protocol used (http: or https:)
window.location.assign; // Loads a new document
window.location.replace; // RReplace the current location with new one.
In JavaScript and jQuery we can use the following code to redirect the one page to another page:
window.location.href="http://google.com";
window.location.replace("page1.html");
ECMAScript 6 + jQuery, 85 bytes
$({jQueryCode:(url)=>location.replace(url)}).attr("jQueryCode")("http://example.com")
Please don't kill me, this is a joke. It's a joke. This is a joke.
This did "provide an answer to the question", in the sense that it asked for a solution "using jQuery" which in this case entails forcing it into the equation somehow.
Ferrybig apparently needs the joke explained (still joking, I'm sure there are limited options on the review form), so without further ado:
Other answers are using jQuery's attr() on the location or window objects unnecessarily.
This answer also abuses it, but in a more ridiculous way. Instead of using it to set the location, this uses attr() to retrieve a function that sets the location.
The function is named jQueryCode even though there's nothing jQuery about it, and calling a function somethingCode is just horrible, especially when the something is not even a language.
The "85 bytes" is a reference to Code Golf. Golfing is obviously not something you should do outside of code golf, and furthermore this answer is clearly not actually golfed.
Basically, cringe.
Javascript:
window.location.href='www.your_url.com';
window.top.location.href='www.your_url.com';
window.location.replace('www.your_url.com');
Jquery:
var url='www.your_url.com';
$(location).attr('href',url);
$(location).prop('href',url);//instead of location you can use window
Here is a time-delay redirection. You can set the delay time to whatever you want:
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Your Document Title</title>
<script type="text/javascript">
function delayer(delay) {
onLoad = setTimeout('window.location.href = "http://www.google.com/"', delay);
}
</script>
</head>
<body>
<script>
delayer(8000)
</script>
<div>You will be redirected in 8 seconds!</div>
</body>
</html>

Search input field not opening in same tab [duplicate]

This question's answers are a community effort. Edit existing answers to improve this post. It is not currently accepting new answers or interactions.
How can I redirect the user from one page to another using jQuery or pure JavaScript?
One does not simply redirect using jQuery
jQuery is not necessary, and window.location.replace(...) will best simulate an HTTP redirect.
window.location.replace(...) is better than using window.location.href, because replace() does not keep the originating page in the session history, meaning the user won't get stuck in a never-ending back-button fiasco.
If you want to simulate someone clicking on a link, use
location.href
If you want to simulate an HTTP redirect, use location.replace
For example:
// similar behavior as an HTTP redirect
window.location.replace("http://stackoverflow.com");
// similar behavior as clicking on a link
window.location.href = "http://stackoverflow.com";
WARNING: This answer has merely been provided as a possible solution; it is obviously not the best solution, as it requires jQuery. Instead, prefer the pure JavaScript solution.
$(location).prop('href', 'http://stackoverflow.com')
Standard "vanilla" JavaScript way to redirect a page
window.location.href = 'newPage.html';
Or more simply: (since window is Global)
location.href = 'newPage.html';
If you are here because you are losing HTTP_REFERER when redirecting, keep reading:
(Otherwise ignore this last part)
The following section is for those using HTTP_REFERER as one of many security measures (although it isn't a great protective measure). If you're using Internet Explorer 8 or lower, these variables get lost when using any form of JavaScript page redirection (location.href, etc.).
Below we are going to implement an alternative for IE8 & lower so that we don't lose HTTP_REFERER. Otherwise, you can almost always simply use window.location.href.
Testing against HTTP_REFERER (URL pasting, session, etc.) can help tell whether a request is legitimate.
(Note: there are also ways to work-around / spoof these referrers, as noted by droop's link in the comments)
Simple cross-browser testing solution (fallback to window.location.href for Internet Explorer 9+ and all other browsers)
Usage: redirect('anotherpage.aspx');
function redirect (url) {
var ua = navigator.userAgent.toLowerCase(),
isIE = ua.indexOf('msie') !== -1,
version = parseInt(ua.substr(4, 2), 10);
// Internet Explorer 8 and lower
if (isIE && version < 9) {
var link = document.createElement('a');
link.href = url;
document.body.appendChild(link);
link.click();
}
// All other browsers can use the standard window.location.href (they don't lose HTTP_REFERER like Internet Explorer 8 & lower does)
else {
window.location.href = url;
}
}
There are lots of ways of doing this.
// window.location
window.location.replace('http://www.example.com')
window.location.assign('http://www.example.com')
window.location.href = 'http://www.example.com'
document.location.href = '/path'
// window.history
window.history.back()
window.history.go(-1)
// window.navigate; ONLY for old versions of Internet Explorer
window.navigate('top.jsp')
// Probably no bueno
self.location = 'http://www.example.com';
top.location = 'http://www.example.com';
// jQuery
$(location).attr('href','http://www.example.com')
$(window).attr('location','http://www.example.com')
$(location).prop('href', 'http://www.example.com')
This works for every browser:
window.location.href = 'your_url';
It would help if you were a little more descriptive in what you are trying to do. If you are trying to generate paged data, there are some options in how you do this. You can generate separate links for each page that you want to be able to get directly to.
<a href='/path-to-page?page=1' class='pager-link'>1</a>
<a href='/path-to-page?page=2' class='pager-link'>2</a>
<span class='pager-link current-page'>3</a>
...
Note that the current page in the example is handled differently in the code and with CSS.
If you want the paged data to be changed via AJAX, this is where jQuery would come in. What you would do is add a click handler to each of the anchor tags corresponding to a different page. This click handler would invoke some jQuery code that goes and fetches the next page via AJAX and updates the table with the new data. The example below assumes that you have a web service that returns the new page data.
$(document).ready( function() {
$('a.pager-link').click( function() {
var page = $(this).attr('href').split(/\?/)[1];
$.ajax({
type: 'POST',
url: '/path-to-service',
data: page,
success: function(content) {
$('#myTable').html(content); // replace
}
});
return false; // to stop link
});
});
I also think that location.replace(URL) is the best way, but if you want to notify the search engines about your redirection (they don't analyze JavaScript code to see the redirection) you should add the rel="canonical" meta tag to your website.
Adding a noscript section with a HTML refresh meta tag in it, is also a good solution. I suggest you to use this JavaScript redirection tool to create redirections. It also has Internet Explorer support to pass the HTTP referrer.
Sample code without delay looks like this:
<!-- Place this snippet right after opening the head tag to make it work properly -->
<!-- This code is licensed under GNU GPL v3 -->
<!-- You are allowed to freely copy, distribute and use this code, but removing author credit is strictly prohibited -->
<!-- Generated by http://insider.zone/tools/client-side-url-redirect-generator/ -->
<!-- REDIRECTING STARTS -->
<link rel="canonical" href="https://yourdomain.example/"/>
<noscript>
<meta http-equiv="refresh" content="0;URL=https://yourdomain.example/">
</noscript>
<!--[if lt IE 9]><script type="text/javascript">var IE_fix=true;</script><![endif]-->
<script type="text/javascript">
var url = "https://yourdomain.example/";
if(typeof IE_fix != "undefined") // IE8 and lower fix to pass the http referer
{
document.write("redirecting..."); // Don't remove this line or appendChild() will fail because it is called before document.onload to make the redirect as fast as possible. Nobody will see this text, it is only a tech fix.
var referLink = document.createElement("a");
referLink.href = url;
document.body.appendChild(referLink);
referLink.click();
}
else { window.location.replace(url); } // All other browsers
</script>
<!-- Credit goes to http://insider.zone/ -->
<!-- REDIRECTING ENDS -->
But if someone wants to redirect back to home page then he may use the following snippet.
window.location = window.location.host
It would be helpful if you have three different environments as development, staging, and production.
You can explore this window or window.location object by just putting these words in Chrome Console or Firebug's Console.
JavaScript provides you many methods to retrieve and change the current URL which is displayed in browser's address bar. All these methods uses the Location object, which is a property of the Window object. You can create a new Location object that has the current URL as follows..
var currentLocation = window.location;
Basic Structure of a URL
<protocol>//<hostname>:<port>/<pathname><search><hash>
Protocol -- Specifies the protocol name be used to access the resource on the Internet. (HTTP (without SSL) or HTTPS (with SSL))
hostname -- Host name specifies the host that owns the resource. For example, www.stackoverflow.com. A server provides services using the name of the host.
port -- A port number used to recognize a specific process to which an Internet or other network message is to be forwarded when it arrives at a server.
pathname -- The path gives info about the specific resource within the host that the Web client wants to access. For example, stackoverflow.com/index.html.
query -- A query string follows the path component, and provides a string of information that the resource can utilize for some purpose (for example, as parameters for a search or as data to be processed).
hash -- The anchor portion of a URL, includes the hash sign (#).
With these Location object properties you can access all of these URL components
hash -Sets or returns the anchor portion of a URL.
host -Sets
or returns the hostname and port of a URL.
hostname -Sets or
returns the hostname of a URL.
href -Sets or returns the entire
URL.
pathname -Sets or returns the path name of a URL.
port -Sets or returns the port number the server uses for a URL.
protocol -Sets or returns the protocol of a URL.
search -Sets
or returns the query portion of a URL
Now If you want to change a page or redirect the user to some other page you can use the href property of the Location object like this
You can use the href property of the Location object.
window.location.href = "http://www.stackoverflow.com";
Location Object also have these three methods
assign() -- Loads a new document.
reload() -- Reloads the current document.
replace() -- Replaces the current document with a new one
You can use assign() and replace methods also to redirect to other pages like these
location.assign("http://www.stackoverflow.com");
location.replace("http://www.stackoverflow.com");
How assign() and replace() differs -- The difference between replace() method and assign() method(), is that replace() removes the URL of the current document from the document history, means it is not possible to use the "back" button to navigate back to the original document. So Use the assign() method if you want to load a new document, andwant to give the option to navigate back to the original document.
You can change the location object href property using jQuery also like this
$(location).attr('href',url);
And hence you can redirect the user to some other url.
Basically jQuery is just a JavaScript framework and for doing some of the things like redirection in this case, you can just use pure JavaScript, so in that case you have 3 options using vanilla JavaScript:
1) Using location replace, this will replace the current history of the page, means that it is not possible to use the back button to go back to the original page.
window.location.replace("http://stackoverflow.com");
2) Using location assign, this will keep the history for you and with using back button, you can go back to the original page:
window.location.assign("http://stackoverflow.com");
3) I recommend using one of those previous ways, but this could be the third option using pure JavaScript:
window.location.href="http://stackoverflow.com";
You can also write a function in jQuery to handle it, but not recommended as it's only one line pure JavaScript function, also you can use all of above functions without window if you are already in the window scope, for example window.location.replace("http://stackoverflow.com"); could be location.replace("http://stackoverflow.com");
Also I show them all on the image below:
Should just be able to set using window.location.
Example:
window.location = "https://stackoverflow.com/";
Here is a past post on the subject: How do I redirect to another webpage?
Before I start, jQuery is a JavaScript library used for DOM manipulation. So you should not be using jQuery for a page redirect.
A quote from Jquery.com:
While jQuery might run without major issues in older browser versions,
we do not actively test jQuery in them and generally do not fix bugs
that may appear in them.
It was found here:
https://jquery.com/browser-support/
So jQuery is not an end-all and be-all solution for backwards compatibility.
The following solution using raw JavaScript works in all browsers and have been standard for a long time so you don't need any libraries for cross browser support.
This page will redirect to Google after 3000 milliseconds
<!DOCTYPE html>
<html>
<head>
<title>example</title>
</head>
<body>
<p>You will be redirected to google shortly.</p>
<script>
setTimeout(function(){
window.location.href="http://www.google.com"; // The URL that will be redirected too.
}, 3000); // The bigger the number the longer the delay.
</script>
</body>
</html>
Different options are as follows:
window.location.href="url"; // Simulates normal navigation to a new page
window.location.replace("url"); // Removes current URL from history and replaces it with a new URL
window.location.assign("url"); // Adds new URL to the history stack and redirects to the new URL
window.history.back(); // Simulates a back button click
window.history.go(-1); // Simulates a back button click
window.history.back(-1); // Simulates a back button click
window.navigate("page.html"); // Same as window.location="url"
When using replace, the back button will not go back to the redirect page, as if it was never in the history. If you want the user to be able to go back to the redirect page then use window.location.href or window.location.assign. If you do use an option that lets the user go back to the redirect page, remember that when you enter the redirect page it will redirect you back. So put that into consideration when picking an option for your redirect. Under conditions where the page is only redirecting when an action is done by the user then having the page in the back button history will be okay. But if the page auto redirects then you should use replace so that the user can use the back button without getting forced back to the page the redirect sends.
You can also use meta data to run a page redirect as followed.
META Refresh
<meta http-equiv="refresh" content="0;url=http://evil.example/" />
META Location
<meta http-equiv="location" content="URL=http://evil.example" />
BASE Hijacking
<base href="http://evil.example/" />
Many more methods to redirect your unsuspecting client to a page they may not wish to go can be found on this page (not one of them is reliant on jQuery):
https://code.google.com/p/html5security/wiki/RedirectionMethods
I would also like to point out, people don't like to be randomly redirected. Only redirect people when absolutely needed. If you start redirecting people randomly they will never go to your site again.
The next paragraph is hypothetical:
You also may get reported as a malicious site. If that happens then when people click on a link to your site the users browser may warn them that your site is malicious. What may also happen is search engines may start dropping your rating if people are reporting a bad experience on your site.
Please review Google Webmaster Guidelines about redirects:
https://support.google.com/webmasters/answer/2721217?hl=en&ref_topic=6001971
Here is a fun little page that kicks you out of the page.
<!DOCTYPE html>
<html>
<head>
<title>Go Away</title>
</head>
<body>
<h1>Go Away</h1>
<script>
setTimeout(function(){
window.history.back();
}, 3000);
</script>
</body>
</html>
If you combine the two page examples together you would have an infant loop of rerouting that will guarantee that your user will never want to use your site ever again.
var url = 'asdf.html';
window.location.href = url;
You can do that without jQuery as:
window.location = "http://yourdomain.com";
And if you want only jQuery then you can do it like:
$jq(window).attr("location","http://yourdomain.com");
This works with jQuery:
$(window).attr("location", "http://google.fr");
# HTML Page Redirect Using jQuery/JavaScript Method
Try this example code:
function YourJavaScriptFunction()
{
var i = $('#login').val();
if (i == 'login')
window.location = "Login.php";
else
window.location = "Logout.php";
}
If you want to give a complete URL as window.location = "www.google.co.in";.
Original question: "How to redirect using jQuery?", hence the answer implements jQuery >> Complimentary usage case.
To just redirect to a page with JavaScript:
window.location.href = "/contact/";
Or if you need a delay:
setTimeout(function () {
window.location.href = "/contact/";
}, 2000); // Time in milliseconds
jQuery allows you to select elements from a web page with ease. You can find anything you want on a page and then use jQuery to add special effects, react to user actions, or show and hide content inside or outside the element you have selected. All these tasks start with knowing how to select an element or an event.
$('a,img').on('click',function(e){
e.preventDefault();
$(this).animate({
opacity: 0 //Put some CSS animation here
}, 500);
setTimeout(function(){
// OK, finished jQuery staff, let's go redirect
window.location.href = "/contact/";
},500);
});
Imagine someone wrote a script/plugin with 10000 lines of code. With jQuery you can connect to this code with just a line or two.
So, the question is how to make a redirect page, and not how to redirect to a website?
You only need to use JavaScript for this. Here is some tiny code that will create a dynamic redirect page.
<script>
var url = window.location.search.split('url=')[1]; // Get the URL after ?url=
if( url ) window.location.replace(url);
</script>
So say you just put this snippet into a redirect/index.html file on your website you can use it like so.
http://www.mywebsite.com/redirect?url=http://stackoverflow.com
And if you go to that link it will automatically redirect you to stackoverflow.com.
Link to Documentation
And that's how you make a Simple redirect page with JavaScript
Edit:
There is also one thing to note. I have added window.location.replace in my code because I think it suits a redirect page, but, you must know that when using window.location.replace and you get redirected, when you press the back button in your browser it will not got back to the redirect page, and it will go back to the page before it, take a look at this little demo thing.
Example:
The process: store home => redirect page to google => google
When at google: google => back button in browser => store home
So, if this suits your needs then everything should be fine. If you want to include the redirect page in the browser history replace this
if( url ) window.location.replace(url);
with
if( url ) window.location.href = url;
You need to put this line in your code:
$(location).attr("href","http://stackoverflow.com");
If you don't have jQuery, go with JavaScript:
window.location.replace("http://stackoverflow.com");
window.location.href("http://stackoverflow.com");
On your click function, just add:
window.location.href = "The URL where you want to redirect";
$('#id').click(function(){
window.location.href = "http://www.google.com";
});
Try this:
location.assign("http://www.google.com");
Code snippet of example.
jQuery is not needed. You can do this:
window.open("URL","_self","","")
It is that easy!
The best way to initiate an HTTP request is with document.loacation.href.replace('URL').
Using JavaScript:
Method 1:
window.location.href="http://google.com";
Method 2:
window.location.replace("http://google.com");
Using jQuery:
Method 1: $(location)
$(location).attr('href', 'http://google.com');
Method 2: Reusable Function
jQuery.fn.redirectTo = function(url){
window.location.href = url;
}
jQuery(window).redirectTo("http://google.com");
First write properly. You want to navigate within an application for another link from your application for another link. Here is the code:
window.location.href = "http://www.google.com";
And if you want to navigate pages within your application then I also have code, if you want.
You can redirect in jQuery like this:
$(location).attr('href', 'http://yourPage.com/');
JavaScript is very extensive. If you want to jump to another page you have three options.
window.location.href='otherpage.com';
window.location.assign('otherpage.com');
//and...
window.location.replace('otherpage.com');
As you want to move to another page, you can use any from these if this is your requirement.
However all three options are limited to different situations. Chose wisely according to your requirement.
If you are interested in more knowledge about the concept, you can go through further.
window.location.href; // Returns the href (URL) of the current page
window.location.hostname; // Returns the domain name of the web host
window.location.pathname; // Returns the path and filename of the current page
window.location.protocol; // Returns the web protocol used (http: or https:)
window.location.assign; // Loads a new document
window.location.replace; // RReplace the current location with new one.
In JavaScript and jQuery we can use the following code to redirect the one page to another page:
window.location.href="http://google.com";
window.location.replace("page1.html");
ECMAScript 6 + jQuery, 85 bytes
$({jQueryCode:(url)=>location.replace(url)}).attr("jQueryCode")("http://example.com")
Please don't kill me, this is a joke. It's a joke. This is a joke.
This did "provide an answer to the question", in the sense that it asked for a solution "using jQuery" which in this case entails forcing it into the equation somehow.
Ferrybig apparently needs the joke explained (still joking, I'm sure there are limited options on the review form), so without further ado:
Other answers are using jQuery's attr() on the location or window objects unnecessarily.
This answer also abuses it, but in a more ridiculous way. Instead of using it to set the location, this uses attr() to retrieve a function that sets the location.
The function is named jQueryCode even though there's nothing jQuery about it, and calling a function somethingCode is just horrible, especially when the something is not even a language.
The "85 bytes" is a reference to Code Golf. Golfing is obviously not something you should do outside of code golf, and furthermore this answer is clearly not actually golfed.
Basically, cringe.
Javascript:
window.location.href='www.your_url.com';
window.top.location.href='www.your_url.com';
window.location.replace('www.your_url.com');
Jquery:
var url='www.your_url.com';
$(location).attr('href',url);
$(location).prop('href',url);//instead of location you can use window
Here is a time-delay redirection. You can set the delay time to whatever you want:
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Your Document Title</title>
<script type="text/javascript">
function delayer(delay) {
onLoad = setTimeout('window.location.href = "http://www.google.com/"', delay);
}
</script>
</head>
<body>
<script>
delayer(8000)
</script>
<div>You will be redirected in 8 seconds!</div>
</body>
</html>

How do I generate SEO-friendly markup for a single-page web app? [duplicate]

There are a lot of cool tools for making powerful "single-page" JavaScript websites nowadays. In my opinion, this is done right by letting the server act as an API (and nothing more) and letting the client handle all of the HTML generation stuff. The problem with this "pattern" is the lack of search engine support. I can think of two solutions:
When the user enters the website, let the server render the page exactly as the client would upon navigation. So if I go to http://example.com/my_path directly the server would render the same thing as the client would if I go to /my_path through pushState.
Let the server provide a special website only for the search engine bots. If a normal user visits http://example.com/my_path the server should give him a JavaScript heavy version of the website. But if the Google bot visits, the server should give it some minimal HTML with the content I want Google to index.
The first solution is discussed further here. I have been working on a website doing this and it's not a very nice experience. It's not DRY and in my case I had to use two different template engines for the client and the server.
I think I have seen the second solution for some good ol' Flash websites. I like this approach much more than the first one and with the right tool on the server it could be done quite painlessly.
So what I'm really wondering is the following:
Can you think of any better solution?
What are the disadvantages with the second solution? If Google in some way finds out that I'm not serving the exact same content for the Google bot as a regular user, would I then be punished in the search results?
While #2 might be "easier" for you as a developer, it only provides search engine crawling. And yes, if Google finds out your serving different content, you might be penalized (I'm not an expert on that, but I have heard of it happening).
Both SEO and accessibility (not just for disabled person, but accessibility via mobile devices, touch screen devices, and other non-standard computing / internet enabled platforms) both have a similar underlying philosophy: semantically rich markup that is "accessible" (i.e. can be accessed, viewed, read, processed, or otherwise used) to all these different browsers. A screen reader, a search engine crawler or a user with JavaScript enabled, should all be able to use/index/understand your site's core functionality without issue.
pushState does not add to this burden, in my experience. It only brings what used to be an afterthought and "if we have time" to the forefront of web development.
What your describe in option #1 is usually the best way to go - but, like other accessibility and SEO issues, doing this with pushState in a JavaScript-heavy app requires up-front planning or it will become a significant burden. It should be baked in to the page and application architecture from the start - retrofitting is painful and will cause more duplication than is necessary.
I've been working with pushState and SEO recently for a couple of different application, and I found what I think is a good approach. It basically follows your item #1, but accounts for not duplicating html / templates.
Most of the info can be found in these two blog posts:
http://lostechies.com/derickbailey/2011/09/06/test-driving-backbone-views-with-jquery-templates-the-jasmine-gem-and-jasmine-jquery/
and
http://lostechies.com/derickbailey/2011/06/22/rendering-a-rails-partial-as-a-jquery-template/
The gist of it is that I use ERB or HAML templates (running Ruby on Rails, Sinatra, etc) for my server side render and to create the client side templates that Backbone can use, as well as for my Jasmine JavaScript specs. This cuts out the duplication of markup between the server side and the client side.
From there, you need to take a few additional steps to have your JavaScript work with the HTML that is rendered by the server - true progressive enhancement; taking the semantic markup that got delivered and enhancing it with JavaScript.
For example, i'm building an image gallery application with pushState. If you request /images/1 from the server, it will render the entire image gallery on the server and send all of the HTML, CSS and JavaScript down to your browser. If you have JavaScript disabled, it will work perfectly fine. Every action you take will request a different URL from the server and the server will render all of the markup for your browser. If you have JavaScript enabled, though, the JavaScript will pick up the already rendered HTML along with a few variables generated by the server and take over from there.
Here's an example:
<form id="foo">
Name: <input id="name"><button id="say">Say My Name!</button>
</form>
After the server renders this, the JavaScript would pick it up (using a Backbone.js view in this example)
FooView = Backbone.View.extend({
events: {
"change #name": "setName",
"click #say": "sayName"
},
setName: function(e){
var name = $(e.currentTarget).val();
this.model.set({name: name});
},
sayName: function(e){
e.preventDefault();
var name = this.model.get("name");
alert("Hello " + name);
},
render: function(){
// do some rendering here, for when this is just running JavaScript
}
});
$(function(){
var model = new MyModel();
var view = new FooView({
model: model,
el: $("#foo")
});
});
This is a very simple example, but I think it gets the point across.
When I instante the view after the page loads, I'm providing the existing content of the form that was rendered by the server, to the view instance as the el for the view. I am not calling render or having the view generate an el for me, when the first view is loaded. I have a render method available for after the view is up and running and the page is all JavaScript. This lets me re-render the view later if I need to.
Clicking the "Say My Name" button with JavaScript enabled will cause an alert box. Without JavaScript, it would post back to the server and the server could render the name to an html element somewhere.
Edit
Consider a more complex example, where you have a list that needs to be attached (from the comments below this)
Say you have a list of users in a <ul> tag. This list was rendered by the server when the browser made a request, and the result looks something like:
<ul id="user-list">
<li data-id="1">Bob
<li data-id="2">Mary
<li data-id="3">Frank
<li data-id="4">Jane
</ul>
Now you need to loop through this list and attach a Backbone view and model to each of the <li> items. With the use of the data-id attribute, you can find the model that each tag comes from easily. You'll then need a collection view and item view that is smart enough to attach itself to this html.
UserListView = Backbone.View.extend({
attach: function(){
this.el = $("#user-list");
this.$("li").each(function(index){
var userEl = $(this);
var id = userEl.attr("data-id");
var user = this.collection.get(id);
new UserView({
model: user,
el: userEl
});
});
}
});
UserView = Backbone.View.extend({
initialize: function(){
this.model.bind("change:name", this.updateName, this);
},
updateName: function(model, val){
this.el.text(val);
}
});
var userData = {...};
var userList = new UserCollection(userData);
var userListView = new UserListView({collection: userList});
userListView.attach();
In this example, the UserListView will loop through all of the <li> tags and attach a view object with the correct model for each one. it sets up an event handler for the model's name change event and updates the displayed text of the element when a change occurs.
This kind of process, to take the html that the server rendered and have my JavaScript take over and run it, is a great way to get things rolling for SEO, Accessibility, and pushState support.
Hope that helps.
I think you need this: http://code.google.com/web/ajaxcrawling/
You can also install a special backend that "renders" your page by running javascript on the server, and then serves that to google.
Combine both things and you have a solution without programming things twice. (As long as your app is fully controllable via anchor fragments.)
So, it seem that the main concern is being DRY
If you're using pushState have your server send the same exact code for all urls (that don't contain a file extension to serve images, etc.) "/mydir/myfile", "/myotherdir/myotherfile" or root "/" -- all requests receive the same exact code. You need to have some kind url rewrite engine. You can also serve a tiny bit of html and the rest can come from your CDN (using require.js to manage dependencies -- see https://stackoverflow.com/a/13813102/1595913).
(test the link's validity by converting the link to your url scheme and testing against existence of content by querying a static or a dynamic source. if it's not valid send a 404 response.)
When the request is not from a google bot, you just process normally.
If the request is from a google bot, you use phantom.js -- headless webkit browser ("A headless browser is simply a full-featured web browser with no visual interface.") to render html and javascript on the server and send the google bot the resulting html. As the bot parses the html it can hit your other "pushState" links /somepage on the server mylink, the server rewrites url to your application file, loads it in phantom.js and the resulting html is sent to the bot, and so on...
For your html I'm assuming you're using normal links with some kind of hijacking (e.g. using with backbone.js https://stackoverflow.com/a/9331734/1595913)
To avoid confusion with any links separate your api code that serves json into a separate subdomain, e.g. api.mysite.com
To improve performance you can pre-process your site pages for search engines ahead of time during off hours by creating static versions of the pages using the same mechanism with phantom.js and consequently serve the static pages to google bots. Preprocessing can be done with some simple app that can parse <a> tags. In this case handling 404 is easier since you can simply check for the existence of the static file with a name that contains url path.
If you use #! hash bang syntax for your site links a similar scenario applies, except that the rewrite url server engine would look out for _escaped_fragment_ in the url and would format the url to your url scheme.
There are a couple of integrations of node.js with phantom.js on github and you can use node.js as the web server to produce html output.
Here are a couple of examples using phantom.js for seo:
http://backbonetutorials.com/seo-for-single-page-apps/
http://thedigitalself.com/blog/seo-and-javascript-with-phantomjs-server-side-rendering
If you're using Rails, try poirot. It's a gem that makes it dead simple to reuse mustache or handlebars templates client and server side.
Create a file in your views like _some_thingy.html.mustache.
Render server side:
<%= render :partial => 'some_thingy', object: my_model %>
Put the template your head for client side use:
<%= template_include_tag 'some_thingy' %>
Rendre client side:
html = poirot.someThingy(my_model)
To take a slightly different angle, your second solution would be the correct one in terms of accessibility...you would be providing alternative content to users who cannot use javascript (those with screen readers, etc.).
This would automatically add the benefits of SEO and, in my opinion, would not be seen as a 'naughty' technique by Google.
Interesting. I have been searching around for viable solutions but it seems to be quite problematic.
I was actually leaning more towards your 2nd approach:
Let the server provide a special website only for the search engine
bots. If a normal user visits http://example.com/my_path the server
should give him a JavaScript heavy version of the website. But if the
Google bot visits, the server should give it some minimal HTML with
the content I want Google to index.
Here's my take on solving the problem. Although it is not confirmed to work, it might provide some insight or idea's for other developers.
Assume you're using a JS framework that supports "push state" functionality, and your backend framework is Ruby on Rails. You have a simple blog site and you would like search engines to index all your article index and show pages.
Let's say you have your routes set up like this:
resources :articles
match "*path", "main#index"
Ensure that every server-side controller renders the same template that your client-side framework requires to run (html/css/javascript/etc). If none of the controllers are matched in the request (in this example we only have a RESTful set of actions for the ArticlesController), then just match anything else and just render the template and let the client-side framework handle the routing. The only difference between hitting a controller and hitting the wildcard matcher would be the ability to render content based on the URL that was requested to JavaScript-disabled devices.
From what I understand it is a bad idea to render content that isn't visible to browsers. So when Google indexes it, people go through Google to visit a given page and there isn't any content, then you're probably going to be penalised. What comes to mind is that you render content in a div node that you display: none in CSS.
However, I'm pretty sure it doesn't matter if you simply do this:
<div id="no-js">
<h1><%= #article.title %></h1>
<p><%= #article.description %></p>
<p><%= #article.content %></p>
</div>
And then using JavaScript, which doesn't get run when a JavaScript-disabled device opens the page:
$("#no-js").remove() # jQuery
This way, for Google, and for anyone with JavaScript-disabled devices, they would see the raw/static content. So the content is physically there and is visible to anyone with JavaScript-disabled devices.
But, when a user visits the same page and actually has JavaScript enabled, the #no-js node will be removed so it doesn't clutter up your application. Then your client-side framework will handle the request through it's router and display what a user should see when JavaScript is enabled.
I think this might be a valid and fairly easy technique to use. Although that might depend on the complexity of your website/application.
Though, please correct me if it isn't. Just thought I'd share my thoughts.
Use NodeJS on the serverside, browserify your clientside code and route each http-request's(except for static http resources) uri through a serverside client to provide the first 'bootsnap'(a snapshot of the page it's state). Use something like jsdom to handle jquery dom-ops on the server. After the bootsnap returned, setup the websocket connection. Probably best to differentiate between a websocket client and a serverside client by making some kind of a wrapper connection on the clientside(serverside client can directly communicate with the server). I've been working on something like this: https://github.com/jvanveen/rnet/
Use Google Closure Template to render pages. It compiles to javascript or java, so it is easy to render the page either on the client or server side. On the first encounter with every client, render the html and add javascript as link in header. Crawler will read the html only but the browser will execute your script. All subsequent requests from the browser could be done in against the api to minimize the traffic.
This might help you : https://github.com/sharjeel619/SPA-SEO
Logic
A browser requests your single page application from the server,
which is going to be loaded from a single index.html file.
You program some intermediary server code which intercepts the client
request and differentiates whether the request came from a browser or
some social crawler bot.
If the request came from some crawler bot, make an API call to
your back-end server, gather the data you need, fill in that data to
html meta tags and return those tags in string format back to the
client.
If the request didn't come from some crawler bot, then simply
return the index.html file from the build or dist folder of your single page
application.

How to hide HTML and other Content in EJS and Node

Having a tough time doing a simple web site in EJS.
I have this set up in my server file:
//Use the .html extension instead of having to name the views as *.ejs
server.engine('.html', require('ejs').__express);
// This avoids having to provide the extension to res.render()
server.set('view engine', 'html');
//set up directory to serve css and javascript files
server.use(Express.static(__dirname, '/views'));
This works great. I have HTML files, I have graphics, I have CSS. I am serving it up with a simple controller that renders the page. Nothing dynamic in these pages. But I do want them protected with an id/password system, and only served up through Express.
The access works fine, I have an end point set up to serve them. I'm forcing log in in that end point. But the problem is, that if someone knows the actual path to those files, they can get at them. So, the access is localhost:8081/admin/documentation/. However, the files are at /views/app_documents. And by entering in localhost:8081/views/app_documents/file_name.html, they can download/view the content, without going through my controls. I moved the content out of views, and grab it in my code, and serve it up, but that doesn't work for images or CSS.
Any suggestions for how to get around this?
Well, the things you find out after the fact.
This:
server.use(Express.static(__dirname, '/views'));
Is very bad. It should be:
server.use(Express.static('./views'));
The way it was, you could download our code, also. So, server.js was available for download. Yikes.
Live and learn.
Still can download the content without going through my authentication, though.
In case anyone else wants to do this, took a while. There are a few problems, as you still need to be able to directly access JS libraries, images and CSS. I found my answer in enter link description here.
The following modifications to that code does the trick. UserIsAllowed checks my permissions system to see if they can access that folder. If they can, no harm, off you go. Otherwise, kill the attempt. They get ACCESS_DENIED back as a string. I can't just kill anyone not going through my code, because then the CSS and images would not work. But this functions nicely. I now am able to serve up content based on my custom permissions system, which is part of a bunch of other administration functions. I can also have multiple different areas based on the URL that are protected by different privileges.
// This function returns a middleware function. It checks to see if the user has access
var protectPath = function(regex)
{
return function(request, response, next)
{
if (!regex.test(request.url)) { return next(); }
userIsAllowed(regex,function(allowed)
{
if (allowed)
{
next(); // send the request to the next handler, which is express.static
}
else
{
response.end('ACCESS_DENIED');
}
});
function userIsAllowed(regex,callback) {
if (regex.test('documentation_website') && request.session.admin_me && _.contains(request.session.admin_me["privileges"],"view_server_documentation")) callback(true);
else callback(false);
}
};
};
server.use(protectPath(/^\/documentation_website\/.*$/));

how to post a value to a php page in a facebook app?

I am a noob facebook app developer and I would be very grateful for a little hand-holding getting started by professionals. I created a very simple app. It's only one file (index.php) and it has an html form that posts a value back to index.php to display. It worked before I added a "share to wall" request to the authentication. Now (I guess) there is a redirection before realoading the index.php, so it gets no $_POST value and it doesn't display the entered value. I would be very grateful if somebody would actually check out my app and its code and tell me how to fix it. (I think it's important to mention that it requests permission to post to the user's wall, but actually it doesn't post anything to the wall. I want to add that functionality later.) Here is the app:
https://apps.facebook.com/webszebb/
And here is the code (screenshot):
http://webszebb.hu/indexphp.png
Thanks.
For the sake of simplicity I'd suggest doing something like:
<html header stuff>
<?php
...snip...
if ($_REQUEST['do'] == 'whatever the action is, i.e: action="?foo" would be foo here') {
print('Your previous number was ' . $_POST['my_number']);
} else {
print('form');
}
?>
But to answer your question I'm assuming the $fb->api('/me') probably redirects you.