Update history state and redirect - javascript

How can I update the history state and then redirect to a new page so that the back button returns to the updated history.
ie:
I go to search.html?query=test
Update history to search.html?waitQuery=test
Redirect to Google search "test"
Hit back button, go to search.html?waitQuery=test
For context: At my work site we use a ticketing system and to speed up my workflow I've created a local script file and set it as a custom search engine in Chrome. It uses regular expressions to check if a query matches a ticket ID pattern and if so will redirect to the ticket system, and if not redirects to Google.
This way if I search something like "TK00123" in the address bar, it redirects to http://ticketengine/query?TK00123 but if I search "hello world" it just forwards that query to Google.
I would like to be able to hit the back button after the redirect and get a sort of interstitial page where I could choose from some options.
This is what I have currently:
<script>
let ticketSearch = 'http://ticketengine/query?'
let googleSearch = 'https://www.google.com/search?q='
if (location.search.match(/\?query=(.+)/)) {
let searchQuery = RegExp.lastParen
history.pushState({}, '', location.pathname + '?waitQuery=' + RegExp.lastParen)
if (searchQuery.match('TK\d+')) {
location.href = ticketSearch + searchQuery
} else {
location.href = googleSearch + searchQuery
}
} else if (location.search.match(/\?waitQuery=(.+)/)) {
let searchQuery = RegExp.lastParen
document.write(`Ticket: ${decodeURIComponent(searchQuery)}<br>`)
document.write(`Google: ${decodeURIComponent(searchQuery)}<br>`)
}
</script>
From everything I've read this seems like it should work, but I never actually get that history entry that I can go back to. The redirect wipes it out.

Related

how can I redirect first timers on the website to the signup page?

Ok so basicly here is my script:
window.onload = () => {
`enter code here` if (**first_time**) {
window.location.href = "www.netlify.app/teamadventures.signup";
}
}
I want to make it so that if it's your first time on the website you get taken to a signup page automatically. How do I do this with vanilla JS?
You can use cookies or localStorage for that. The localStorage is the easiest method. First check if there is something stored on it with getItem. If not, store this information (the user visited the page) in localStorage with setItem and redirect the page to the Sign Up.
var first_time = localStorage.getItem("first_time");
if (!first_time){
localStorage.setItem("first_time", 1);
window.location.href = "www.netlify.app/teamadventures.signup";
}

How to get Previous visited page URL in Javascript? [duplicate]

Is there any way to get the previous URL in JavaScript? Something like this:
alert("previous url is: " + window.history.previous.href);
Is there something like that? Or should I just store it in a cookie? I only need to know so I can do transitions from the previous URL to the current URL without anchors and all that.
document.referrer
in many cases will get you the URL of the last page the user visited, if they got to the current page by clicking a link (versus typing directly into the address bar, or I believe in some cases, by submitting a form?). Specified by DOM Level 2. More here.
window.history allows navigation, but not access to URLs in the session for security and privacy reasons. If more detailed URL history was available, then every site you visit could see all the other sites you'd been to.
If you're dealing with state moving around your own site, then it's possibly less fragile and certainly more useful to use one of the normal session management techniques: cookie data, URL params, or server side session info.
If you want to go to the previous page without knowing the url, you could use the new History api.
history.back(); //Go to the previous page
history.forward(); //Go to the next page in the stack
history.go(index); //Where index could be 1, -1, 56, etc.
But you can't manipulate the content of the history stack on browser that doesn't support the HTML5 History API
For more information see the doc
If you are writing a web app or single page application (SPA) where routing takes place in the app/browser rather than a round-trip to the server, you can do the following:
window.history.pushState({ prevUrl: window.location.href }, null, "/new/path/in/your/app")
Then, in your new route, you can do the following to retrieve the previous URL:
window.history.state.prevUrl // your previous url
document.referrer is not the same as the actual URL in all situations.
I have an application where I need to establish a frameset with 2 frames. One frame is known, the other is the page I am linking from. It would seem that document.referrer would be ideal because you would not have to pass the actual file name to the frameset document.
However, if you later change the bottom frame page and then use history.back() it does not load the original page into the bottom frame, instead it reloads document.referrer and as a result the frameset is gone and you are back to the original starting window.
Took me a little while to understand this. So in the history array, document.referrer is not only a URL, it is apparently the referrer window specification as well. At least, that is the best way I can understand it at this time.
<script type="text/javascript">
document.write(document.referrer);
</script>
document.referrer serves your purpose, but it doesn't work for Internet Explorer versions earlier than IE9.
It will work for other popular browsers, like Chrome, Mozilla, Opera, Safari etc.
If anyone is coming from React-world, I ended up solving my use-case using a combination of history-library, useEffect and localStorage
When user selects new project:
function selectProject(customer_id: string, project_id: string){
const projectUrl = `/customer/${customer_id}/project/${project_id}`
localStorage.setItem("selected-project", projectUrl)
history.push(projectUrl)
}
When user comes back from another website. If there's something in localStorage, send him there.
useEffect(() => {
const projectUrl = localStorage.getItem("selected-project")
if (projectUrl) {
history.push(projectUrl)
}
}, [history])
When user has exited a project, empty localStorage
const selectProject = () => {
localStorage.removeItem("selected-project")
history.push("/")
}
I had the same issue on a SPA Single Page App, the easiest way I solved this issue was with local storage as follows:
I stored the url I needed in local storage
useEffect(() => {
const pathname = window.location.href; //this gives me current Url
localstorage.setItem('pageUrl',JSON.stringify(pathname))
}, []);
On the next screen (or few screens later) I fetched the url can replaced it as follows
useEffect(() => {
const pathname = localstorage.getItem('pageUrl');
return pathname ? JSON.parse(pathname) : ''
window.location.href = pathname; //this takes prevUrl from local storage and sets it
}, []);
Those of you using Node.js and Express can set a session cookie that will remember the current page URL, thus allowing you to check the referrer on the next page load. Here's an example that uses the express-session middleware:
//Add me after the express-session middleware
app.use((req, res, next) => {
req.session.referrer = req.protocol + '://' + req.get('host') + req.originalUrl;
next();
});
You can then check for the existance of a referrer cookie like so:
if ( req.session.referrer ) console.log(req.session.referrer);
Do not assume that a referrer cookie always exists with this method as it will not be available on instances where the previous URL was another website, the session was cleaned or was just created (first-time website load).
Wokaround that work even if document.referrer is empty:
let previousUrl = null;
if(document.referrer){
previousUrl = document.referrer;
sessionStorage.setItem("isTrickApplied",false);
}else{
let isTrickApplied= sessionStorage.getItem("isTrickApplied");
if(isTrickApplied){
previousUrl = sessionStorage.getItem("prev");
sessionStorage.setItem("isTrickApplied",false);
}else{
history.back(); //Go to the previous page
sessionStorage.setItem("prev",window.location.href);
sessionStorage.setItem("isTrickApplied",true);
history.forward(); //Go to the next page in the stack
}
}

URL routing not working when user clicks a link

I am trying to modify a web application we have and I'm not sure if I can do what is being requested. My boss wants to be able to click a link from an email and have our internal company web application go straight to a page identified at the end of a provided URL.
If I click on the link below the first time, it goes to the index page of our web application. If I leave the web application open and click on the link again, it goes to the correct page identified at the end of the URL.
http://mycompanyweb.com/handbook/mycompanyprocess/#/rt/softwate/9.13_UpdateSDP
I've tried adding an init(), thinking that is where the application goes first in the lifecycle and I only see this part of the URL at that point (http://mycompanyweb.com/handbook/mycompanyprocess/). This leads me to believe that the browser is stripping everything off after the # when it first opens. Is that correct? Is there something I can do to get our web application to go directly to the document the first time a user clicks on the link, without the web application open?
http://mycompanyweb.com/handbook/mycompanyprocess/ - Base URL
#/rt - Used by our javascript engine to determine which path to take
(dev or production).
/software/9.13_UpdateSDP - Logical path to a web page named 6.034_UpdateSDP.htm
Our engine that determines where to route based on the URL. I assume that the second time a link is clicked that it goes to the correct page is because the engine has been loaded (provided the browser is left open when clicked a second time).
$(document).ready(function () {
// Define the routes.
Path.map("#/:program").to(function () {
var program = this.params['program'];
if (program == "search") {
$("#mainContent").load("search.html");
}
else {
$("#mainContent").load("views/onepageprocess.html");
}
$("#subheader").html("");
$("#headerLevelTwoBreadcrumbLink").html("");
}).enter(setPageActions);
Path.map("#/:program/:swimlane").to(function () {
localStorage.removeItem("SearchString");
var swimlane = this.params['swimlane'];
var view = "views/" + swimlane + ".html";
$("#mainContent").load(view);
}).enter(setPageActions);
// Sends all links to the level three view and updates the breadcrumb.
Path.map("#/:program/:swimlane/:page").to(function () {
var page = this.params['page'];
var url = "views/levelthree/" + page.replace("", "") + ".htm";
var levelThreeTitle = "";
$.get(url)
.done(function () {
// Nothing here at this time...
}).fail(function () {
url = "views/levelthree/badurlpage.htm";
levelThreeTitle = "Page Unavailable";
}).always(function (data) {
$("#subheader").html("");
level_three_breadcrumb = "views/breadcrumbs/breadcrumb_link.html";
$("#headerLevelTwoBreadcrumbLink").load(level_three_breadcrumb);
$("#headerLevelThreeBreadcrumb").html("");
$('#headerLevelThreeBreadcrumb').append('<img src="images/Chevron.gif" />');
if (data.status != "404") {
$("#headerLevelThreeBreadcrumb").append(retrieveStorageItem("LevelThreeSubheader"));
}
$("#mainContent").load(url);
});
}).enter(setPageActions);
// Set a "root route". User will be automatically re-directed here. The definition
// below tells PathJS to load this route automatically if one isn't provided.
Path.root("#/rt");
// Start the path.js listener.
Path.listen();
});
Is there something I can do to get our web application to go directly to the document the first time a user clicks on the link, without the web application open?
If anyone runs into something like this, I found out that my company's servers were stripping anything after the # in the URL at authentication. I will be modifying my app to not use hash tags in the URL to fix it.

Extracting page id from a facebook page url

I have an application where when a user enters their facebook fan page url, I extract the page id and store that into the database to be used later in facebook graph api.
I have added the following js to extract page id:
<script>
var fburl= "https://www.facebook.com/audi";
if(fburl.indexOf("?") != -1) {
var fburl_new=fburl.split("/");
var fburl_newer=(fburl_new[fburl_new.length-1])
var fburl_newer =fburl_newer.split("?");
var fbnameonly=(fburl_newer[fburl_newer.length-2]);
} else {
var fbnameonly = fburl.substring(fburl.lastIndexOf('/') + 1);
}
if(fbnameonly==undefined) {
console.log(fburl);
}else {
console.log(fbnameonly);
}
</script>
So, if I a user enters a facebook url like: https://www.facebook.com/audi, I get the output audi which is fine.
If a user enters facebook url as : https://www.facebook.com/pages/abc-def/1234568, I get the output 1234568 which is fine.
but for urls like:
https://www.facebook.com/abc-def-12345678/ (should return 12345678)
or
https://www.facebook.com/audi/timeline?ref=page_internal (should return audi)
I am unable to get the page id, is there any better way by which I can extract page id from any facebook fan page url and use it in facebook graph api like: https://graph.facebook.com/page_id dynamically ?
I figured out a better way to get page id from any facebook page url, I am not sure if there is even better option to do this but here is the code what I have used:
$fbUrl = "https://www.facebook.com/Lo-stile-di-Anna-1521824524722026";
$graphUrl = "https://graph.facebook.com/?id=".$fbUrl."&access_token=xxxxx&fields=id";
$output = file_get_contents($graphUrl);
$output = json_decode($output, TRUE);
echo $output["id"]; // returns 1521824524722026
I tried this with various facebook urls and it worked everytime, hope this helps someone in the future.

Adding Browser History and Navigation To JavaScript DOM Page Change Function

I am using JavaScript to change the pages of my website, but I am running into the issue where I can't use browser navigation to go back or forwards through the history once I have changed pages.
I have tried adding a /#pagename to the URL for each page, and a few other things, but I can't seem to find something that works. I need to be able to make sure that the browser is saving the history of the page changes I make, so it can navigate those pages with the forward and back buttons.
// Change Page Function
function ChangeContent (page) {
var pages={"homepage":{title: "homepage"},"servicespage":{title: "servicespage"}};
//Show home page
for(var homepage in pages) {
if(page!==homepage) {
document.getElementById(homepage).style.display='none';
}
else {
document.getElementById(homepage).style.display='block';
window.scrollTo(0,0);
}
}
//Show services page
for(var servicespage in pages) {
if(page!==servicespage) {
document.getElementById(servicespage).style.display='none';
}
else {
document.getElementById(servicespage).style.display='block';
window.scrollTo(0,0);
}
}
}
You should look at window.history.pushState to add history entries and window.onpopstate to react to the user travelling "backward" through the entries you've added.
When you want to "change" pages, make a call like:
window.history.pushState( stateData, title, url );
where...
stateData is some object containing data you define
title is a string name for the new state
url is the string to which the browser's url should be changed
For example, if you want to change to "servicespage" and make the url change to "/#services":
window.history.pushState( { title: "Services" }, "servicespage", "/#services" );
Note that you still have to manipulate the DOM at this point.
Then, if you want to react to the user going backward through history:
window.onpopstate = function( event ) {
var data = event.state;
// data references the first argument of 'pushState'
// do whatever showing or hiding of <div>s here
};

Categories

Resources