How can i run JavaScript inside my webpage only once? - javascript

So I am trying to implement an auto language changer for my webpage.
But it keeps refreshing the page as it keeps running.
I want to run this script only once so it doesn't refresh my page forever.
I have this script:
var language = navigator.language || navigator.userLanguage;
language = language.substring( 0, 2 );
if (language == "pt" || "pt-BR" || "pt-PT"){
window.location.href = "index.html";
}
else {
window.location.href = "indexEN.html"; //
}
And its called by:
<!-- Auto Language -->
<script src="js/language.js"></script>

Think about it as if you have an infinite loop, like while (true) {} — what you need to do is break out of the loop at some point. To break out of this loop, you need to add a check to make sure you're not already on the intended page. That will stop the constant redirection.
var language = navigator.language || navigator.userLanguage
language = language.substring(0, 2)
var ptPage = 'index.html'
var enPage = 'indexEN.html'
// you're calling substring, so no need to check the variants
// your check was also incorrect :)
if (language == "pt") {
if (window.location.pathname !== '/' + ptPage) {
window.location.href = ptPage
}
} else if (window.location.pathname !== '/' + enPage) {
window.location.href = enPage
}

Refreshing the page is part of your code, as you can see here
var language = navigator.language || navigator.userLanguage;// get users default language
language = language.substring( 0, 2 );
if (language == "pt" || "pt-BR" || "pt-PT"){
window.location.href = "index.html";
}
else {
window.location.href = "indexEN.html"; //loading another html file for users who use english
}
So since you are reloading another html file, your javascript IS going to run again. A solution to this would be to make your webpage a SPA (single page application). That way you wouldn't have to reload anything (including javascript). You can also change page content and headers without actually loading a new file. SPA's are usually done in react (with react routing) but you can make then vanilla JS too.
https://medium.com/altcampus/implementing-simple-spa-routing-using-vanilla-javascript-53abe399bf3c

Don't know if it is a best practice but you can use localStorage.
if((localStorage.getItem('pageLoaded') ?? 'true') === 'true') {
alert('dsds')
localStorage.setItem('pageLoaded', 'false')
}
The alert will be executed once

Related

Javascript: Modern working approach to refresh the page redirects to another location

I have tried some answers on SO, but they are old and no longer work, or are blocked by the browser.
I have a login, and a separate login failed page (separate for a good reason, please don't say make them the same page).
If the user is shown the failed login page, and they hit refresh, I would like to go to the login page, not refresh the failed login page.
Existing answers go something like this:
<script type="module">
function redirect()
{
window.location.href="/login/";
return true;
}
window.addEventListener('beforeunload', redirect);
</script>
Not ideal, but instead of catching the reload before navigating away, catch the reload at the start of the page:
Reload detection code from: https://stackoverflow.com/a/53307588/5506400
<script type="module">
const pageAccessedByReload = (
(window.performance.navigation && window.performance.navigation.type === 1) ||
window.performance
.getEntriesByType('navigation')
.map((nav) => nav.type)
.includes('reload')
);
if (pageAccessedByReload) {
window.location.href="/login/";
}
</script>
let me know this will help or not, use type value to check for reload
// Use getEntriesByType() to just get the "navigation" events
var entries = performance.getEntriesByType('navigation');
for (var i = 0; i < entries.length; i++) {
console.log('= Navigation entry[' + i + ']');
var p = entries[i];
// dom Properties
console.log(
'DOM content loaded = ' +
(p.domContentLoadedEventEnd - p.domContentLoadedEventStart)
);
console.log('DOM complete = ' + p.domComplete);
// other properties
console.log('type = ' + p.type);
}

Run function based on .pathname

So I've got this code in my page: a very simple but working script to translate it to several languages.
// preparing language file
var aLangKeys=new Array();
aLangKeys['en']=new Array();
aLangKeys['es']=new Array();
aLangKeys['fr']=new Array();
aLangKeys['cn']=new Array();
aLangKeys['en']['language']='english';
aLangKeys['es']['language']='español';
aLangKeys['fr']['language']='français';
aLangKeys['cn']['language']='中文';
aLangKeys['en']['buy']='buy';
aLangKeys['es']['buy']='comprar';
aLangKeys['fr']['buy']='acheter';
aLangKeys['cn']['buy']='买';
$(document).ready(function() {
// onclick behavior
$('.language').click(function() {
var lang = $(this).attr('id'); // obtain language id
if ($(this).attr('id') == 'es') {
$('.language').attr('id', 'fr');
}
else if ($(this).attr('id') == 'fr') {
$('.language').attr('id', 'cn');
}
else if ($(this).attr('id') == 'cn') {
$('.language').attr('id', 'en');
}
else if ($(this).attr('id') == 'en') {
$('.language').attr('id', 'es');
}
// translate all translatable elements
$('.translate').each(function(i){
$(this).html(aLangKeys[lang][ $(this).attr('key') ]);
});
} );
});
// HERE'S WHERE MY BRAIN STARTS MALFUNCTIONING
if ((window.location.pathname).split('/')[1] == 'es') {
// <-- EXECUTE FUNCTION ABOVE TO TRANSLATE TO SPANISH BASED ON PATHNAME
}
else if ((window.location.pathname).split('/')[1] == 'fr') {
// <-- EXECUTE FUNCTION ABOVE TO TRANSLATE TO FRENCH BASED ON PATHNAME
}
else {
}
So it basically translates (changes the value of certain elements on the page) when clicking a button. Every time you click on it, changes to the next language. That works fine.
THE PROBLEM is, I want it 'automatically' changed to a certain language if the user is visiting from a certain link:
Example:
www.mysite.com (nothing happens because nothing is on the pathname)
www.mysite.com/es/ ('automatically changes values to spanish')
www.mysite.com/fr/ ('automatically changes values to french')
I tried 'faking' the button click with javascript but didnt work.
Also tried 'naming' the translating function and 'call/run' it.
I know it's easier to do and I'm making it complicated but I'm such a noob.
Please, help. Or just a hint. Thanks in advance and sorry for my English.
Based on code above a couple thoughts:
1) lets change aLangKeys to an object with each key being another object.
i.e.
var aLangKeys={};
aLangKeys['en']={}; // Thats a named key/prop so we want an object here
...
aLangKeys['en']['language']='english'; // ditto the above comment
2) we probably want to move the logic that checks for locality inside the ready function.
I.e.
$(document).ready(function() {
// onclick behavior
$('.language').click(function() {
...
});
// we want access to the DOM *and* maybe certain functions that do stuff. So its gotta be in here...
if ((window.location.pathname).split('/')[1] == 'es') {
// <-- EXECUTE FUNCTION ABOVE TO TRANSLATE TO SPANISH BASED ON PATHNAME
}
else if ((window.location.pathname).split('/')[1] == 'fr') {
// <-- EXECUTE FUNCTION ABOVE TO TRANSLATE TO FRENCH BASED ON PATHNAME
}
}); // end of ready function
Couple reasons:
a) we want to change the page content based on info like pathname/locality. So we want to know the page is loaded first.
b) perhaps we will want to make a function that does language processing/changing and call that from multiple places. We want that function in scope of our locality checking logic. If we define that inside the ready function scope, we will need any logic that calls that function also inside the same scope

JQuery, .attr - Remember state using cookies after page reload

I wrote a function that changes logo to minimised version of it when I click on a button by changing attribute of an image. Also, after another click on the same button, logo switches back to original.
Everything is as I expected but I have a problem when I refresh the page. When I refresh the page, the browser just switches the logo back to original. So, I want the browser to remember if logo is switched and remember that state after reload of page. Please see my code below. I've seen similar solutions here but I don't know how to implement it in my code.
How can I set and use cookies for this?
$('#changeLogo').click(function() {
if ($(".logo").attr('src') === "files/img/logo-min.png") {
$(".logo").attr('src', "files/img/logo.png");
}
else {
$(".logo").attr('src', "files/img/logo-min.png");
}
});
Localstorage is a better option for this:
$(function(){
$('#changeLogo').click(function() {
var logoSrc;
if ($(".logo").attr('src') === "files/img/logo-min.png") {
logoSrc = "files/img/logo.png";
}
else {
logoSrc = "files/img/logo-min.png";
}
$(".logo").attr('src', logoSrc);
localStorage.setItem("logoSrc", logoSrc);
});
if ( typeof localStorage.logoSrc !== "undefined" )
$(".logo").attr('src', localStorage.logoSrc);
});
$(document).ready(function(){
var logo = localStorage.getItem('logo');
if(logo != null){
$(".logo").attr('src', logo);
}
$('#changeLogo').click(function() {
if ($(".logo").attr('src') === "files/img/logo-min.png") {
$(".logo").attr('src', "files/img/logo.png");
}
else {
$(".logo").attr('src', "files/img/logo-min.png");
}
localStorage.setItem('logo',$(".logo").attr('src'));
});
});
Set src in localStorage and on page load get the value and set the src again to logo.
You can set cookies using javascript api: https://www.w3schools.com/js/js_cookies.asp
Or use an easier api like this:
https://github.com/js-cookie/js-cookie
So in the if/else you can save the currently used link of the logo to a cookie:
//set
Cookies.set('logo-path', 'files/img/logo-min.png');
//get
Cookies.get('logo-path');
You could also utilize local storage (https://www.w3schools.com/html/html5_webstorage.asp) but it is not guaranteed that it will work on older browsers.
If you want to use cookies, you can use the JQuery plugin http://plugins.jquery.com/cookie/
Then :
$(document).ready(function(){
if (typeof $.cookie('logo') === 'undefined')
$.cookie('logo', "files/img/logo-min.png");
$('#changeLogo').click(function() {
if ($.cookie('logo') === "files/img/logo-min.png") {
$.cookie('logo', "files/img/logo.png");
} else {
$.cookie('logo', "files/img/logo-min.png");
}
$(".logo").attr('src', $.cookie('logo'));
});
});

How to check where the code redirect in a PHP and jquery project

I am working on a open source e-shop called Prestashop.
The problem is, when I disable a module, the site will auto refresh. I would like to know which part of the code and file caused the problem.
Here is the site:
prestigefood.com.hk/zh/
Are there any way to check through browser's developer console / tools to see:
Redirect caused by JS / PHP?
Where is that part of code
The redirect is caused by a JS function inside /js/tools.js :
function autoUrl(name, dest)
{
var loc;
var id_list;
id_list = document.getElementById(name);
loc = id_list.options[id_list.selectedIndex].value;
if (loc != 0)
location.href = dest+loc;
return ;
}
Or
function autoUrlNoList(name, dest)
{
var loc;
loc = document.getElementById(name).checked;
location.href = dest + (loc == true ? 1 : 0);
return ;
}
It will be your work to find where it's called ;)

Chrome extension logic is not wοrking

I've managed to get most of my Chrome extension working, but there is a problem I can't work out.
You can grab it here if you want and load it as an unpacked extension.
After loading it works like this.
You are prompted that they need to enter a URL on the options page.
You enter a URL (e.g. http://example.com) on the options page as asked and click save, and then when you click the icon in the toolbar you can see the web page appear in the popup.
If you then go and removes the URL from the options page and clicks save, then the popup does not show the original prompt page they saw at the beginning.
I think this code (from popup.js) is at fault, but I can't see why it won't work.
var url = localStorage.url;
var alturl = chrome.extension.getURL("need-to-enter-url.html");
var element = document.getElementById("testerURL");
if (url != undefined || url != null) {
element.src = url;
} else {
element.src = alturl;
};
When you "remove" the url you are actually saving an empty string. localStorage.url = "" so your value checking is failing. I would also recommend tweaking the if logic to be clearer.
Use something like this:
if (url === undefined || url === null || url === "") {
element.src = alturl;
} else {
element.src = url;
}
Optionally you can rely on JavaScript's truthiness.
if (url) {
element.src = url;
} else {
element.src = alturl;
}

Categories

Resources