I want to remove my scripts file after it executes. It should be removed from all session. I linked file in functions.php for child theme:
function tutsplus_enqueue_custom_js() {
wp_enqueue_script('custom', get_stylesheet_directory_uri().'/scripts/redirect.js');
}
As I said - it should be executed only once in whole session, not page. I know that it should be done with unlink but I don't know how to write a condition that will remove this file from whole session only when it was executed . Can you help me?
new script:
let executed = window.sessionStorage.getItem("sessionCodeExecuted")
console.log(executed)
if (executed != 1) {
let uri = window.location;
let lang = window.navigator.language;
if( uri.href.indexOf('lang') < 0) {
if ((lang != 'ru-RU') && (lang != 'ru')){
eng = window.location.href.includes('https://www.site/en/');
if (eng == false){
let re = "https://www.site/";
let url = window.location.href;
let newstr = url.replace(re, 'https://www.site/en/');
newstr += "?currency=USD";
window.location.href = newstr;
}
}
}
window.sessionStorage.setItem("sessionCodeExecuted", 1);
}
You can use sessionStorage to check if the script has been executed and store this info there. Then, do a check if the value exists. If it does, prevent the code from executing on next page reload. Please note that when you close and reopen the browser, the code will execute again (it seems this is exactly what you need).
(function(){
let executed = window.sessionStorage.getItem("sessionCodeExecuted");
if (!sessionStorage.getItem('sessionCodeExecuted')) {
sessionStorage.setItem('sessionCodeExecuted', 'yes');
}
if (executed) return;
/* below script will execute only once during the current browser session. */
let uri = window.location;
let lang = window.navigator.language;
if (uri.href.indexOf('lang') < 0) {
if ((lang != 'ru-RU') && (lang != 'ru')) {
eng = window.location.href.includes('https://www.site/en/');
if (eng == false) {
let re = "https://www.site/";
let url = window.location.href;
let newstr = url.replace(re, 'https://www.site/en/');
newstr += "?currency=USD";
window.location.href = newstr;
}
}
}
})();
Related
I am creating a website for a client at the moment, we decided an easy way to store "items" which will be passed down to a subdomain from the root would be to store them as cookies. This works perfectly fine in a normal browser, yet when I tested it on a native device browser it didn't work as smoothly. I am wondering where some of these problems may have been coming from and hoping you wonderful developers can lend a man a hand.
The idea is that on the frontend when a "Your Order" side drawer is pressed, a function runs grabbing the cookies and then sorts them into their specified content area's -> Downloadable Content, Requested Material and Bespoke Content. I have created two separate functions for this, one that was the original working piece and another more tailored and "good practice".
Tried having the "Value" of the cookie containing the values that need to be stored such as, [itemname],[itemlocation], [itemdescription], [itemtype].
The second function stores the item data in an object, the object is then JSON.stringified and iterated over in a for loop. This is then taken out of a string with JSON.parse() and further iterated over in an .each() iterating over the index(key) and val(value).
FIRST FUNCTION:
$('section#review-downloads a.toggle-btn').bind('click tap', function() {
let cookies;
let itemSplit;
var section = $('section#review-downloads');
if(section.hasClass('active')) {
section.removeClass('active');
setTimeout(function() {
$('section#review-downloads .selected-items div').find('p').remove();
}, 900);
} else {
section.addClass('active');
$.each(document.cookie.split(';'), function() {
cookies = this.split('=');
let trimId = cookies[0].trim();
vals = cookies[1].replace(/[\])}[{(]/g, '');
if(!(cookies[0] === "envFilter")) {
$.each(vals.split('[ ]'),function() {
itemSplit = this.split(',');
let itemId = trimId;
let itemName = itemSplit[0];
let itemUrl = itemSplit[1];
let itemType = itemSplit[2];
let itemDesc = itemSplit[3];
if(itemType === ' Downloadable Content ') {
$('<p id="selected-item-'+itemId+'"><strong>'+itemName+'</strong>'+itemDesc+'</p>').appendTo('section#review-downloads .review-container .selected-items .downloadable-content');
} else if (itemType === ' Requested Materials ') {
$('<p id="selected-item"><strong>'+itemName+'</strong>'+itemDesc+'</p>').appendTo('section#review-downloads .review-container .selected-items .requested-material');
} else if (itemType === ' Bespoke Content ') {
$('<p id="selected-item"><strong>'+itemName+'</strong>'+itemDesc+'</p>').appendTo('section#review-downloads .review-container .selected-items .bespoke-content');
}
});
};
});
}
return false;
});
THE SECOND FUNCTION (best practice)
$('div.support-item-wrapper div.order-add').bind('click tap', function() {
let id = $(this).data('id');
let name = $(this).data('title');
let file = $(this).data('file');
let type = $(this).data('type');
let desc = $(this).data('description').replace(/(\r\n|\n|\r)/gm, "");
let url = $(this).data('url');
let cookieVal = {
name: name,
file: file,
type: type,
desc: desc,
url: url
};
let string = JSON.stringify(cookieVal);
setCookie('product-'+id, string, 1);
});
$('section#review-downloads a.toggle-btn').bind('click tap', function() {
var section = $('section#review-downloads');
if(section.hasClass('active')) {
section.removeClass('active');
} else {
section.addClass('active');
let decoded_user_product;
cookie_values = document.cookie.split(';');
for(i = 0; i < cookie_values.length; i++) {
cookie_split = cookie_values[i].split("=");
cookie_key = cookie_split[0].trim();
cookie_value = cookie_split[1].trim();
// console.log(cookie_value);
if(cookie_key != "envFilter") {
decoded_user_product = JSON.parse(cookie_value);
}
$.each(decoded_user_product, function(index, val) {
// console.log("index:" + index + "& val:" + val);
if(index === "name") {
console.log(val);
} else if (index === "type") {
console.log(val);
} else if (index === "desc") {
console.log(val);
}
});
}
// console.log(decoded_user_product);
};
});
On Desktop, the results are perfectly fine. Each item is easily console.log()'able and has been easily sorted in the FIRST FUNCTION.
On Mobile, the same results were as to be expected. But after realising it hadn't worked I used chrome://inspect along with a lot of console.logs to come to the conclusion that I may be too inexperienced to understand what parts of my code are unable to run on a native browser.
I have a list or URLs that I need to add a body class to. The list of URLs are found in the queryStrings variable. Here is my current code:
var myUrl = window.location.href;
var queryStrings = ["www.site.com/test", "www.site.com/test2"];
var allPresent = CheckIfAllQueryStringsExist(myUrl, queryStrings);
if (allPresent == false) {
} else {
document.body.classList.add("module-ads");
}
function CheckIfAllQueryStringsExist(url, qsCollection) {
for (var i = 0; i < qsCollection.length; i++) {
if (url.indexOf(qsCollection[i]) == -1) {
return false;
}
}
return true;
}
Right now, allPresent equals false even if I am on the page www.site.com/test.
Your CheckIfAllQueryStringsExist is wrong.
Change it to:
function CheckIfAllQueryStringsExist(url, qsCollection) {
for (var i = 0; i < qsCollection.length; i++) {
if (url.indexOf(qsCollection[i]) != -1) {
return true;
}
}
return false;
}
Your are checking the URL to see if it contains the array, which is backward.
Also, you don't need any loops here. Just check the array for the existence of the current URL and instead of an empty true branch to your first if statement, just reverse the test logic so that you can just have one branch.
var myUrl = window.location.href;
var queryStrings = ["www.site.com/test", "www.site.com/test2"];
var allPresent = CheckIfAllQueryStringsExist(myUrl, queryStrings);
if (allPresent) {
document.body.classList.add("module-ads");
}
function CheckIfAllQueryStringsExist(url, qsCollection) {
// Just return whether the array contains the url
return qsCollection.indexOf(url) > -1;
}
take a look at the window.location object, that will give you many other ways to match your url.
https://developer.mozilla.org/en-US/docs/Web/API/Location
href will return the protocol, so you could just tack on "https://" + to each href check, or you could use location.pathname or something.
You can use an array function .includes() to do your check. Otherwise, #gaetanoM answer is the answer you're looking for.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes
var myUrl = window.location.href;
var queryStrings = ["www.site.com/test", "www.site.com/test2"];
var allPresent = queryStrings.includes(myUrl);
if (allPresent == false) {
// do something
} else {
document.body.classList.add("module-ads");
}
In my project I need to use close event in browser through web, server and database deal with the information when user log out.
I do not know how to catch the event and distinguish close and refresh event.
I tried these code:
window.onbeforeunload = function() {
var n = window.event.screenX - window.screenLeft;
var b = n > document.documentElement.scrollWidth-20;
if(b && window.event.clientY < 0 || window.event.altKey) {
alert("close event");
}else{
alert("refresh event");
}
}
But it only catches the refresh event.
Is there a better way to solve the problem?
Besides,I have read the How to differentiate browser close and refresh events in Chrome?,but it doesn't give me the answer.
An idea: Judge by cookie to get the information if it is log in.
And the browser usually doesn't disable cookies.
If the cookie is disable, you may ask user to enable it.
Here is an example for cookie:
function setCookie(name, value) //cookies setting
{
var argv = setCookie.arguments;
var argc = setCookie.arguments.length;
var expires = (argc > 2) ? argv[2] : null;
if(expires!=null)
{
var LargeExpDate = new Date ();
LargeExpDate.setTime(LargeExpDate.getTime() + (expires*1000*3600*24));
}
document.cookie = name +value }
//In Js
setCookie("a","34234523542");
//read cookie:
function WM_readCookie(name)
{
//if there is no cookie,return false;or get value and return value
if(document.cookie == '')
return false;
else
return
unescape(WM_getCookieValue(name));
}
function WM_getCookieValue(name)
{
// Declare variables.
var firstChar,lastChar;
// Get the entire cookie string.
// (This may have other
name=value pairs in it.)
var theBigCookie = document.cookie;
// Grab
just this cookie from theBigCookie string.
// Find the start of
'name'.
firstChar = theBigCookie.indexOf(name);
// If you found it,
if(firstChar != -1)
{
// skip 'name' and '='.
firstChar +=
name.length + 1;
// Find the end of the value string (i.e. the next
';').
lastChar = theBigCookie.indexOf(';', firstChar);
if(lastChar == -1) lastChar = theBigCookie.length;
// Return the
value.
return theBigCookie.substring(firstChar, lastChar);
} else
{
// If there was no cookie, return false.
return false;
}
}
I'm making a FF extension and I hit a snag. Here's what I have:
var canLink = document.querySelector('link[rel="service"]').href;
This finds a link with rel="service" and it works great. However, if the page does not have a link with rel=service, it returns null and breaks out of the rest of the program. How can I make it so that if canLink = null, it doesn't break?
Is there a way to catch this error?
Here is the file. Line 12 is self.port.emit, which works fine.
//Get link if it exists
var elem = document.querySelector('link[rel="service"]').href,
canLink = elem ? elem.href : "";
if (canLink){
self.port.emit("link", canLink);
}
else {
canLink = "";
self.port.emit("link", canLink);
}
Use a simple condition
var elem = document.querySelector('link[rel="service"]');
var canLink = elem ? elem.href : "";
Now in your code you could check in your code for "" (empty string) and take further measures like
if(canLink !== "") { // could be just written as if(canLink){ ... }
// do something with the canLink now
}
In jQuery how can I check if a user is visiting a particular direct id link url?
For example:
http://mydomain.com/#foo
I this case, I like to check for foo.
Would love something like:
if(jQuery.urlHasHash("foo")) {
//logic here
}
No need for jQuery, your browser gives you all you need with document.location.hash
If you want to check if such an ID exists on your page:
var hash = document.location.hash.replace(/^#/, '');
if (document.location.hash != '' && document.getElementById(hash) {
// or just: $(document.location.hash)
// ...
}
Try this Demo http://jsfiddle.net/7QceB/
This might fit your needs :)
Code
$(function(){
//var href = location.href; // get the url
var href = "http://mydomain.com/#foo"; // example url
var split = href.split("#"); // split the string; usually there'll be only one # in an url so there'll be only two parts after the splitting
var afterSplit = "Error parsing url";
if(split[1] != null){
afterSplit = split[1];
}
// If everything went well shows split[1], if not then de default error message is shown
alert(afterSplit);
});
Try my jsFiddle : jsFiddle here
// it might be from browser & / anywhere else
var url = "http://mydomain.com/#foo";
url = url.split('#').pop().split('?').pop();
var page = url.substring(url.lastIndexOf('/') + 1);
console.log(page); // foo
or just
var url = "http://mydomain.com/#foo";
var page = url.substring(url.lastIndexOf('/') + 1); // #foo
After you can use if statement to know if (page == "foo")