Cookie based on page path - javascript

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.

Related

Stuck in a conditional redirect loop

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||'";
}

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#=#'.

php remove single variable value pair from querystring

I have a page that lists out items according to numerous parameters ie variables with values.
listitems.php?color=green&size=small&cat=pants&pagenum=1 etc.
To enable editing of the list, I have a parameter edit=1 which is appended to the above querystring to give:
listitems.php?color=green&size=small&cat=pants&pagenum=1&edit=1
So far so good.
When the user is done editing, I have a link that exits edit mode. I want this link to specify the whole querystring--whatever it may be as this is subject to user choices--except remove the edit=1.
When I had only a few variables, I just listed them out manually in the link but now that there are more, I would like to be able programmatically to just remove the edit=1.
Should I do some sort of a search for edit=1 and then just replace it with nothing?
$qs = str_replace("&edit=1, "", $_SERVER['QUERY_STRING']);
<a href='{$_SERVER['PHP_SELF']}?{$qs}'>return</a>;
Or what would be the cleanest most error-free way to do this.
Note: I have a similar situation when going from page to page where I'd like to take out the pagenum and replace it with a different one. There, since the pagenum varies, I cannot just search for pagenum=1 but would have to search for pagenum =$pagenum if that makes any difference.
You can use parse_str() to parse the query string, remove the unwanted parts and build the new one via http_build_query() like this
parse_str($_SERVER['QUERY_STRING'], $params);
unset($params['edit']);
$new_query_string = http_build_query($params);

Getting the thread id in Gmail

I'm looking for a way to figure out how to get the thread id for a particular email on Gmail, just before it is sent OR at the point where the send button is clicked.
Currently, I'm working with Javascript in order to scrape other items off the email and store them in a record which works pretty well for everything except the thread id.
The thread ID can be found after I send the email within the URL:
https://mail.google.com/mail/u/0/?shva=1#inbox/13ddda647539dcca
In this case, the thread id (if I'm right - is 13ddda647539dcca.
Any help would be appreciated.
If anyone is still interested - You can retrieve the thread id after the email is sent by observing the that appears at the top of the page. This span contains a link which has an attribute named 'param' which has the thread-id.
You could try:
var matched = window.location.hash.match(/[A-Za-z0-9]+$/);
if (matched) {
// Found alphanumeric string at end of hash
}
And you can get the value with matched[0].
window.location.hash should only grab the "#inbox/13ddda647539dcca" part. Then the regex is to match against any alphanumeric characters at the end of the string. So the fact that "inbox" is separated from the thread id by a "/" is important.
Of course, all of this depends on the reliability of Gmail keeping the URL following the same convention as it currently seems to be.

Categories

Resources