Stuck in a conditional redirect loop - javascript

I want the application to change the url in the browser to set the parameters if the parameters do not match the item value on initial load of the page.
I tried to create a conditional check to see if the substring matched anywhere within the URL. However, I get caught in a loop. Something tells me my use of wildcards is incorrect.
htp.p('<script>
if(window.location.href !== "*'||:P4_TEAM||'*") {
window.location.href = "https://apextserverurl/ords/f?p=80001:4:::::P4_TEAM:'||:P4_TEAM||'"
}
</script>');
Since the page item cannot be null, the thought is on the initial load, it will push the parameters into the URL and adjust accordingly. The actual result shows the url parameters load into the browser correctly, but it seems to fail the logic test on the javascript and keeps refreshing instead

Your page refreshes endlessly, because your if condition will always be true (Because you can't use wildcards in JavaScript...at least not like that) and window.location.href will reload your page.
You could use a Regex, but for your example a simple string.includes() is sufficient.
You can just check with includes() like so:
// If ':P4_TEAM' is not in the url
if(!window.location.href.includes(':P4_TEAM')) {
// Set the url to the provided string (and refresh the page)
window.location.href = "https://apextserverurl/ords/f?p=80001:4:::::P4_TEAM:'||:P4_TEAM||'";
}

Related

Cookie based on page path

Is it possible to set a cookie value, as the url page path?
i.e I have a cookie that is set when someone clicks a button with the ID mybtn but I'd like the value of the cookie to be automatically generated based on the last part of the page path. For example if the user clicked the button whilst on a page www.myweb.com/cars/car1 the value of the cookie should be set as car1. The code below is where I've got to so far, but it's the "THEPAGEPATH" where I'm stuck as I guess I need to use javascript to pull the url information.
<script>$("#mybtn").bind("click", function() {
document.cookie="model=THEPAGEPATH;path=/;"
});</script>
Simple solution would be to just split the string, and take the last part of it.
<script>$("#mybtn").bind("click", function() {
const strings = window.location.href.split("/").filter(str => !!str)
document.cookie=`model=${strings[strings.length - 1]};path=/;`
});</script>
This works for both routes with and without trailing slash. It does not work for routes that have query parameters that contains slashes. If you need to support that, you could split the string on ?, and the use the same logic on the first part of the string.

Passing variable when opening another html page using JavaScript

This is probably a really silly question, but I can't find it online anywhere and I've been looking for at least an hour.
I have a link Instruments which I want to get the ID of it once clicked, as I need to pass some variable to the page I am opening to know that the instruments link was clicked. This is being called from productInformation.html
I have also tried doing Instruments and then in my JavaScript, window.open("MusicMe.html", "_self"); and then tried passing a variable that way, but still absolutely no luck. Any help as to how I would pass a variable back to the page when it opens would be brilliant.
Once it opens, I am using the variable to set the ID of an element so it only displays a certain set of the information, which is working on it's own, but when I go back to try and call it, it's always thinking it is showing them all as I cannot work out how to set the variable to define it. Unfortunately I need to use JavaScript not PHP.
Thanks.
I would just tell you some ways, hope you would be able to implement it:
Use query params to pass the variable.
When you're navigating to another page, add query params to the url.
window.open("MusicMe.html?variable=value", "_self");
In your next page, check for queryParam by getting window.location.href and using regex to split the params after ? and get that data.
Use localStorage/cookies
Before navigating to the next page, set a variable in your localStorage
localStorage.setItem("variable","value");
window.open("MusicMe.html", "_self");
In your second page, in the window load event.
$(function() {
if(localStorage.getItem("variable")) {
// set the ID here
// after setting remember to remove it, if it's not required
localStorage.removeItem("variable");
}
});
You can use localStorage to keep the value, or use parameter like
href="MusicMe.html?id=111"
to pass the value to new page.
You can always pass a GET variable in you re URL just like this myhost.com?var=value
You can get the value of this variable by parsing the URL using Js see this
How can I get query string values in JavaScript?
You can simply pass # value into url, get it and then match it with 'rel' attribute given on specified element.
Here I have done materialize collapsible open from link on another page.
JS:
var locationHash = window.location.hash;
var hashSplit = locationHash.split('#');
var currentTab = hashSplit[1];
$('.collapsible > li').each(function() {
var allRels = $(this).attr('rel');
if(currentTab == allRels){
$(this).find('.collapsible-header').addClass('active');
$(this).attr('id',currentTab);
}
});

HTML Append Variable to Query String

I have http://localhost/?val=1
When I click on a link, is there a way this link can append a query variable to the current string, for example:
Link
so when I click it the url would be:
http://localhost/?val=1&var2=2
but when I click the link it removes the first query string and looks like
http://localhost/&var2=2
Is such a thing possible with normal HTML?
You can't do that using only html, but you can do it with js or php:
Using JS:
<a onclick="window.location+=((window.location.href.indexOf('?')+1)?'':'?')+'&var2=2'">Link</a>
Using Php:
Link
Notice 1: make sure you don't have the new variable in the current link, or it'll be a loop of the same variable
Notice 2: this is not a professional way, but it could work if you need something fast.
Basically you want to get your current URL via JavaScript with:
var existingUrl = window.location.href; // http://localhost/?val=1
Then append any Query Strings that are applicable using:
window.location.href = existingUrl + '&var2=2';
or some other similar code. Take a look at this post about Query Parameters.
Note: A link would already have to exist with an OnClick event that calls a function with the above code in it for it to work appropriately.
Now obviously this isn't very useful information on it's own, so you are going to want to do some work either in JavaScript or in Server code (through use of NodeJS, PHP, or some other server-side language) to pass those variable names and their values down so that the button can do what you are wanting it to do.
You will have to have some logic to make sure the query parameters are put in the URL correctly though. I.E. if there is only one query param it's going to look like '?var1=1' and if it's any subsequent parameter it's going to look like '&var#=#'.

Ok, I got my query string now how to remove it without page refreshing

I got my query string in document. ready but then I want to remove it and save value in a global variable without refreshing the page, but it just never happens..
var globalVar = null;
$(document).ready(function () {
name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
results = regex.exec(location.search);
results == null ? null : decodeURIComponent(results[1].replace(/\+/g, " "));
if (results != null)
globalVar = results[1];
window.location.search = '';
});
This code keeps reloading page forever
Edit
Here is what is happening,
User gets email to a link, to select right row in table on the site, we are using querystring as using hash doesn't work (TMG server removes it), so once user gets on the site, we don't need query string anymore as we are using hash (because hash don't refresh page on change.)
Edit 2
Why don't want to keep query string and hash ?
because I can update hash without refresh whereas updating querystring refreshes the page :(, so i don't want it to be like
www.example.com/sites/fruitstore?fruitid=123#fruitid=432
You need to use the history api instead of just setting the location to something new.
https://developer.mozilla.org/en-US/docs/Web/Guide/API/DOM/Manipulating_the_browser_history
pushstate or replaceState will allow you to change the url displayed in the browser without a page refresh.
This script could also help you out: https://github.com/browserstate/history.js/
I think your "reloading" problem comes from this line:
window.location.search = ''
This SO answer will give you the good method to handle browser URL history:
you'll need the history API of modern browsers, to concrete, pushState will do it.
reference
and you'll probably want to use a library, as f.e. history.js, as handling different browsers can be very tricky...
Use the history API for this:
window.history.replaceState({}, document.title,
window.location.href.split('?')[0]);
replaceState replaces the current history entry with the given values. The first parameter is a data parameter, which is not used in this example. The second parameter is the window title. The final parameter is the new URL. The split takes everything before the beginning of the query parameters. If you need things that follow a #, then you'll have to use a more complicated URL re-building function.
replaceState does not add a new entry to history, which keeps you from filling the history with useless values.
See this answer for more information.
window.location.search = '';
This code keeps reloading page forever
Yeah, obviously. Instead, use
if (location.search != '')
location.search = '';
once user gets on the site, we don't need query string anymore as we are using hash (because hash don't refresh page on change.)
You also might want to try the history API, so that you always have a copy-and-pastable querystring URL in the location bar.

replace current url without reloading the page

I want to take the current URL from browser and replace the last number param by other number, my example URL:
app#!folder/1/document?p=1
the param to replace - ?p=1 into ?p=3
the param number is generated dynamically so I have to take the param from URL
I want to execute this JavaScript as String,
thanks a lot for any help
I reslove the problem(VAADIN FRAMEWROK) without using javascript
String url = Page.getCurrent().getUriFragment().toString();
url = url.replaceAll("\\?p=([0-9])?", "?p=1");
Page.getCurrent().setUriFragment(url, true);
Unless I'm missing something, just use String#replace() like so
url = url.replace("?p=1", "?p=3");
Note that a modification to the current URL will reload the page unless it happens in the hash part (after the # character), which is obviously what you're trying to do.
The current URL can be modified in javascript via the location.href variable:
location.href = location.href.replace("p=1", "p=3");

Categories

Resources