I am very new to JavaScript. I am trying to make a web application, where a simple back button will go to a specific page I am looking for, one that has the word "search" in it. I don't know the exact URL, because the parameters within that URL change, and I need to keep it consistent to what the user wanted. But this one button should go back to that one page, regardless of the other links that were clicked.
For example:
If I clicked on
Home Page
Main Page
Page 1
Page 1.3
Back
I want the back to always take me to Main Page with the exact parameters it had before, not Home Page.
I tried the following:
The button itself
movieTableBodyElement.append('' + " << Back" + ''); // Building the HTML button, calls the goBackHelper() function
function goBackHelper()
{
// checks if the page directly behind is the Main Page with "search"
if(document.referrer.includes("search"))
{
// if its the main page, exit the function and end recursive call
window.history.go(-1);
}
else
{
// it is not the last page, so go to the past page and check again
window.history.go(-1);
goBackFunction();
}
}
But this takes me to the very first home page. I thought that document.referrer would get me the past URL, but it doesn't seem to be working for me. Is there a way to get the URL from past pages? So if I am on page 2, can I get all the URLs and search for Main Page? Any help is greatly appreciated!
I'm also new to Stack Overflow, so if there is any clarification please don't hesitate to let me know!
document.referrer is not the same as the actual URL in all situations.
Your best bet is to store the URLs in sessionStorage.
Add this snippet of code to your pages:
if (sessionStorage.getItem("locationHistory") !== null) {
var locationHistoryArray = JSON.parse(sessionStorage.getItem("locationHistory"));
locationHistoryArray.push(window.location.href);
sessionStorage.setItem("locationHistory", JSON.stringify(locationHistoryArray));
} else {
var locationHistoryArray = [];
locationHistoryArray.push(window.location.href);
sessionStorage.setItem("locationHistory", JSON.stringify(locationHistoryArray));
}
And this is your goBackHelper() function :
function goBackHelper() {
var searchString = 'search'; //modify this
var locationHistoryArray = JSON.parse(sessionStorage.getItem("locationHistory"));
for (i = 0; i < locationHistoryArray.length; i++) {
if (locationHistoryArray[i].includes(searchString)) {
window.location.assign(locationHistoryArray[i]);
break;
}
}
}
Read about document.referrer here.
Related
So I am trying to make a back button using onclick="history.back()". But the thing is when I enter my website using an external link, and press the back button, it takes me back to the previous page which is external. I know that it has been programmed to do so. But is there any way to prevent it from taking users back to the external website?
One way would be to store in the sessionStorage the history.length value that you received when first visiting the page.
Then you will store the current index in the history.state. Once you reach back the initial index, you'd prevent the history to go back.
// To be executed on all the pages of your domain
// check if we already saved it
let min_index = sessionStorage.getItem("minHistoryIndex");
// otherwise
if (min_index === null) {
// store it
min_index = history.length;
sessionStorage.setItem("minHistoryIndex", min_index);
}
// first time we come to this history status
if (!history.state ) {
history.replaceState({ index: history.length }, "");
}
const button = document.querySelector("button");
// if we reached the limit saved in sessionStorage
if (history.state.index === +min_index) {
button.disabled = true;
button.title = "Going back once more would take you out of our website";
}
else {
button.onclick = (evt) => history.back();
}
Live demo - source
One problem with this is that if your user decides to go to an other origin from your page and then go back to it manually, you could go back to that external domain, but I guess it's such a corner case that it can be accepted in most cases.
I am trying to track Facebook ad results using the Facebook Pixel during appropriate events (page views, lead generation, order form view, purchase). I can do all of this for GA using GTM with no problem, but on Facebook I only have partial success.
The main issue is I have a cross domain setup as shown below:
domain1.com/offer - landing page (FB Page View Pixel should fire)
domain1.com/ordergate - request email before showing order form page (FB Page View Pixel should fire)
crm.com/formsubmission - the actual form submits to my crm (FB Lead Pixel should fire)
crm.com/orderform - order form (FB order form view pixel should fire)
domain1.com/thankyou - the thank you page (FB order pixel should fire)
So my trigger on GTM to fire FB pixel was the "referrer" containing "facebook". However, because of the multi-step process, the referrer is lost by the time the order form or sale is completed.
I have since then learned I need to do the following:
User lands from facebook, write cookie with an appropriately short expiration time that stores this information on domaiin1.com.
When the user clicks a link and is redirected to crm.com, check if the user has the cookie, and if they do, add something like ?reffacebook=true to the redirect URL.
On crm.com, if the URL has ?reffacebook=true write the same cookie you wrote on (1) with an equally short expiration time.
UPDATE
So I have figured out step 2 using the following script on page view when the Facebook cookie is set:
function updateLinks(parameter, value)
{
var links = document.getElementsByTagName('a');
var includeDomains = self.location.host;
for (var i=0;i<links.length;i++)
{
if(links[i].href != "#" && links[i].href != "/" && links[i].href != "" && links[i].href != window.location) //Ignore links with empty src attribute, linking to site root, or anchor tags (#)
{
var updateLink = true;
if(links[i].href.toLowerCase().indexOf(includeDomains.toLowerCase()) != -1) //Domain of current link is included i the includeDomains array. Update Required...
{
updateLink = false;
}
if(!updateLink)
{
//Do nothing - link is internal
}
else
{
var queryStringComplete = "";
var paramCount = 0;
var linkParts = links[i].href.split("?");
if(linkParts.length > 1) // Has Query String Params
{
queryStringComplete = "?";
var fullQString = linkParts[1];
var paramArray = fullQString.split("&");
var found = false;
for (j=0;j<paramArray.length;j++)
{
var currentParameter = paramArray[j].split("=");
if(paramCount > 0)
queryStringComplete = queryStringComplete + "&";
if(currentParameter[0] == parameter) //Parameter exists in url, refresh value
{
queryStringComplete = queryStringComplete + parameter + "=" + value;
found = true;
}
else
{
queryStringComplete = queryStringComplete + paramArray[j]; //Not related parameter - re-include in url
}
paramCount++;
}
if(!found) //Add new param to end of query string
queryStringComplete = queryStringComplete + "&" + parameter + "=" + value;
}
else
{
queryStringComplete = "?" + parameter + "=" + value;
}
links[i].href = links[i].href.split("?")[0] + queryStringComplete;
}
}
else
{
//Do nothing
}
}
}
So with this code I can now properly attribute people with the facebook referral across domains...
...but I still have a problem with form submits.
So when the contact gets to step 4, it is a redirect from the form submission. It does not carry any cookie or query string, so neither of the FB pixels (order form view or order) is being fired.
I'm not sure how I would handle this. My first thought is to pass a hidden field into the form submission (say reffacebook=true). Then somehow expose that in the url in a form of a query string so that it can be detected by GTM.
This seems to be somewhat complicated though, as I would have to edit all my forms to have this variable, edit my CRM so it knows to receive it, and then edit the form landing page to expose that variable in the url.
Hey I hope that I understood what is this all about. Here you want to track traffic between cross domains right? I am not into any coding or anything like that to achieve such a tracking. Because I don't know any coding seriously (I apologies my self for not even trying to learn. I realize my self is that knowing Java script have a lot of benefits in advanced marketing). Ok Here is my point. If we want to track traffic between domains and retarget them later, wouldn't it be done by Facebook itself just by using the same pixel in both domains? This is what I used to believe in the case of multiple domains while doing Facebook ads. Here the important Thing is the audience should be the same from domain A to domain B (In your case it looks like yes the audience is same there for there is no issue for doing that I think). But not sure whether Facebook will track the traffic between domains successfully or not just by placing same FB Pixel in both domains.
Thank you.
#SalihKp, I think you have a point however the issue is that i believe facebook does cross domain with third party cookies which are not working optimally now adays
#David Avellan actually since the user returns to the landing domain for the thank you page, then the final conversion should work using 1st party cookies, but what you want in between might be an issue.
i am looking at now a case where they user lands on a.com and convert
I'm redirecting the user from another page when they click the "Edit" button using the code below.
$('#editListButton').click(function(){
window.location.href = "http://localhost/yyy.php"; //redirect
// Changes that need to be made
$('#defaultText').remove();
$('#orderList').append('<p' + 'message' + '</p>');
});
The page redirects to the predefined link, after which I need update a html <div> tag with text. But the code coming from the other page does nothing. How can change the text in the div tag?
Pass it in the url.
$('#editListButton').click(function(){
window.location.href = "http://localhost/yyy.php?message"; //redirect
});
Then on the other page
var url = window.location.href.split('?');
var msg = url[1];
$('#defaultText').remove();
$('#orderList').append('<p>' + msg + '</p>');
Once you've triggered an operation that's going to reload the entire page, browsers (not all, but it seems like most) will just quit doing anything to the current page, essentially ignoring any DOM updates from the event loop.
To get around this, it generally works to delay the redirect with a short timeout:
setTimeout(function() {
window.location.href = "http://localhost/yyy.php";
}, 1);
Now the browser doesn't know that the page is to be reloaded, so it'll obey your DOM update request.
edit — If what you're expecting (and it's not really clear from the OP, but it's hinted at in a comment below) is that the code after updating the location should affect the new page, well that's just not how things work. You can put that code in the new page (and pass parameters via the URL you're loading, if necessary) and have it run there, or else you can change the architecture completely and load your new code via ajax.
There are many ways to pass information from one page to another. To give an idea of the concept, somewhat in relation to the question posted, here's one:
Page A:
$('#editListButton').click(function(){
window.location.href = "http://localhost/yyy.php?action=remove&value=" +
encodeURIComponent('ashdahjsgfgasfas');
});
Page B:
var action = /(?:\?|&)action=([^&$]+)/.exec(location.search)
if ( 'remove' === action[1] ) {
var value = /(?:\?|&)value=([^&$]+)/.exec(location.search)
$('#defaultText').remove();
$('#orderList').append('<p>' + value[1] + '</p>');
}
Here's the scenario:
I have a link on "page1.html" that i want to get displayed on an iframe of another link "page2.html" .
How do I do this?
Fourth and final try!
The problem with your page is the following
Your problem is that your link [See adoptable dogs] points to http://hssv.convio.net/PageServer?pagename=adoption_available?http://adopt.hssv.org/search/searchResults.asp?task=search&searchid=&advanced=&s=adoption&animalType=3%2C16&statusID=3&submitbtn=Find+Animals
When I go to
http://hssv.convio.net/PageServer?pagename=adoption_available,
I'm redirected to
http://hssv.convio.net/site/PageServer?pagename=page_not_found
Therefore I assume the correct link is http://hssv.convio.net/site/PageServer?pagename=adoption_available (yup, that loaded a page correctly, you were missing /site/ within the link)
Now the second part of your problem. Your page that contains an iframe expected the name of the page to load into the iframe to be everything after the '?', which was fine before since you were't using any other params in the URL (actually not fine, since it breaks easily)
so your link should be (note that the url passed as a parameter should be url encoded)
http://hssv.convio.net/site/PageServer?pagename=adoption_available&content=http%3A%2F%2Fadopt.hssv.org%2Fsearch%2FsearchResults.asp%3Ftask%3Dsearch%26searchid%3D%26advanced%3D%26s%3Dadoption%26animalType%3D3%2C16%26statusID%3D3%26submitbtn%3DFind%2BAnimals
And your page containing the iframe should modify LoadContent to the following.
function LoadContent() {
var url = getParams()['content'];
if (url) {
LoadIFrame(url);
}
}
function getParams() {
var paramMap = {};
if (location.search.length == 0) {
return paramMap;
}
var parts = location.search.substring(1).split("&");
for (var i = 0; i < parts.length; i ++) {
var component = parts[i].split("=");
paramMap [decodeURIComponent(component[0])] = decodeURIComponent(component[1]);
}
return paramMap;
}
Lastly, I don't want to sound rude, but it seems like you need to do some studying before you are assigned to modify these pages. These are all very basic concepts of HTML, HTTP, and JS. Some debugging would easily identify your problem and it had nothing to do with what you asked initially, it was simply that you modified code without a clue to what it was doing...
I was on Facebook and realised that when I change page the page address changes but the page does not redirect but loads via ajax instead.
You can tell because the console does not clear when you click the link but the URL changes.
Weird, but anyone know how it is done?
Facebook runs with massive AJAX calls that changes the page state and the sections.
So to make a page linkable to somebody by copying the URL address, every time you call an AJAX relevant function they updates the URL using a fake anchor "#!" plus the real address.
Simply when you load the real page (using F5 or linking that so somebody) a JS parser catchs the string after #! (if there is) and redirect you to baseaddress + that.
I belive something like this (untested):
var urlstr = new String(location.href);
var urlparm = urlstr.split('#!');
var last = urlparm.length - 1;
if( (urlparm[last] != urlparm[0]) && (urlparm[last] != "/") )
{ var redir = "http://www.facebook.com" + urlparm[last];
location.href = redir;
}
In Google Chrome instead the URL really changes, I'm according that there is an hash somewhere, but I don't know where and how.