Infinite loop when redirecting in Javascript - javascript

I have a sample page, let' say testpage.pl When I choose English version, GET parameter is added to URL, like /?language=en.
Afterwards, when I click menu positions, they are in the English version so everything is OK.
But if I want to have English version of a subpage directlty after pasting URL in a browser, like
http://testpage.pl/wyjazdy-i-przyjazdy/erasmus-incoming-staff/accommodation.html)
the Polish version is opened. So I've made a simple redirect function like below, but it comes to the loop after first start. This function redirect to the same page, but before it tries to redirect to this first URL with GET parameter ?language=en
How to solve this?
function cleanUrl() {
window.location = "http://testpage.pl/?language=en";
var cleanedUrl = "http://testpage.pl/wyjazdy-i-przyjazdy/erasmus-incoming-staff/accommodation.html";
var currentUrl = window.location.href;
if (currentUrl !== cleanedUrl) {
window.location = cleanedUrl;
}
}
cleanUrl();

Your are updating url in first line of function which is causing your code to loop infinite. Remove that line or move to some other function for fix
function cleanUrl() {
var cleanedUrl = "http://testpage.pl/wyjazdy-i-przyjazdy/erasmus-incoming-staff/accommodation.html";
var currentUrl = "http://testpage.pl/?language=en";
if (currentUrl !== cleanedUrl) {
window.location = cleanedUrl;
}
}
cleanUrl();

Keep the window.location assignment as last operation.
function cleanUrl() {
var enUrl = "http://testpage.pl/?language=en";
var cleanedUrl = "http://testpage.pl/wyjazdy-i-przyjazdy/erasmus-incoming-staff/accommodation.html";
var currentUrl = window.location.href;
if( currentUrl !== cleanedUrl ) { enUrl = cleanedUrl; }
window.location = enUrl;
}

Related

Can't redirect to url by javascript function

I need a button, which lead up in url path like this:
from /host/elements/1
to /host/elements
I have a link in my html:
And a javascript function:
function go_backward() {
var url = window.location.href;
var page = url.substring(0, url.lastIndexOf('/'))
window.location.assign(page);
return false;
}
But when i click the button i only get desired url printed, without correct redirect.
Why cat it be so?
Change:
window.location.assign(page);
return false;
to
window.location.href = page;
If you just want to go back you can also use:
window.history.go(-1)

Go to the given URL (if we not there), show the form and scroll to it

So I have this piece of code where the form is hidden until I click on the element. If I'm in that page (profile.php) it shows the form and scrolls down to it but if I'm not on that page (e.g: index.php) it goes to thatpage(profile.php) but doesn't show the form and doesn't scroll down to it until I click again on that element (which it is in the menu)
So here is my html code:
<a id='showForm'>Apply</a>
<div class="formL" style="display:none">
//code
</div>
and here's my script:
<script>
$('#showForm').click(function() {
let currentURL = $(location).attr("href");
let redirectURL = "http://127.0.0.1/dealaim/profile.php#formL"
if (currentURL !== redirectURL) {
$(location).attr("href", redirectURL);
var formL = $('.formL').show();
document.documentElement.scrollTop = formL[0].offsetTop;
} else {
var formL = $('.formL').show();
document.documentElement.scrollTop = formL[0].offsetTop;
}
</script>
The code after your redirect won't do anything; that code needs to run on the page you redirect to, not the page doing the redirect.
Once the redirect takes place, it's a question of passing along some info that the page can receive and use to automatically invoke the function. So:
$('#showForm').click(function() {
let currentURL = location.href;
let redirectURL = "http://127.0.0.1/dealaim/profile.php?showForm=1"
if (currentURL !== redirectURL)
location = redirectURL;
else {
let formL = $('.formL').show();
document.documentElement.scrollTop = formL[0].offsetTop;
}
});
if (location.href.includes('showForm=1') $('#showForm').click();
Note also there's no point at all in doing $(location).attr('href') - you just unnecessarily invoke jQuery and wrap what is a simple object-and-property combo in its API. Just use location.href.

prepend to url of page using javascript

I need all blog product pages to show in a popup. In order to show in the popup their url must be in the form https://expample.com?/modal-link=blog_page_url. (I'm using the plugin and this is the requirement)
I would like to write a code in javascript that checks the URL. If the URL of the page contains the word 'product' I would like prepend to the url: https://expample.com?/modal-link= inorder to enable it to be shown in a popup.
I'm using the code below:
if(window.location.href.indexOf("product") > -1) {
var url = window.location.href;
url_new = 'https://example.com/?modal-link=' + url
} else {
}
window.location.href = url_new;
The is creating a new URL but it is causing it to be added an infinite amount of time.
How should I be doing this?
Follow on question: (should I open a new question for this?)
I would like to adapt the code so the page does not reload during the redirect.
I know there are other posts about this eg How do I modify the URL without reloading the page? or https://stackoverflow.com/questions/3338642/updating-address-bar-with-new-url-without-hash-or-reloading-the-pagebut could someone please help me modify my javascript code for this specific case?
Would I need to use the lines below?
document.location.hash = 'afterhash';
history.pushState('data to be passed', 'Title of the page', '/test');
I'm at a loss which part of my code need to go where in the above lines.
Your recursion is missing a stop condition. For example, if "some_product" contains "product" and you prepend anything to it, it will still contain "product", as in "really_some_product", "really_really_some_product", etc. You can see where this is going, infinite recursion.
So, you need to tell it to stop at some point, which is when the new url already starts with what you intend to prepend to the original one.
Following this, since there's a case in which we don't change anything, we should also not redirect.
var url = window.location.href,
prepend_to_url = "https://example.com/?modal-link=",
url_new = false;
if (url.indexOf(prepend_to_url) == 0) {
// url starts with what we prepend
// so do nothing
} else if(url.indexOf("product") > -1) {
url_new = prepend_to_url + url;
}
if (url_new) { // don't redirect unless we've done something above
window.location.href = url_new;
}
A more concise version of the code above could look like this:
var url = window.location.href,
prepend_to_url = "https://example.com/?modal-link=",
url_new = false;
if (url.indexOf(prepend_to_url) == -1 // url doesn't start with what we prepend
&& url.indexOf("product") > -1 // and our condition is met
) {
url_new = prepend_to_url + url;
}
url_new && (window.location.href = url_new); // equivalent to an "if" statement
What you need is to get the query parameter part of the url by using substr with index of ? to the end of the url
var url_new;
if(window.location.href.indexOf("product") > -1) {
var url = window.location.href.substr(window.location.href.indexOf("?") +1, window.location.href.length);
var newValue = 10;
url_new = 'https://example.com/?modal-link=' + newValue + "&" + url
}
console.log(url_new);
You should initilize the url_new and change it for some condition:
let url_new = window.location.href
if(window.location.href.indexOf("product") > -1) {
url_new = 'https://example.com/?modal-link=' + window.location.href;
}
window.location.href = url_new;

Part of the javascript is not running

The JS below runs accordingly, but it never hits the last function (showAllTabIdRedirect). Any idea why? Is it my syntax? I am trying to run the first function that grabs the primary tab id and then use that to pass along some other functions. In the end, I would redirect the user as well as refresh a specific tab.
<script>
function refreshDetailsTab() {
sforce.console.getEnclosingPrimaryTabId(focusDetailSubtabRedirect);
var formsId;
var currentUrl = window.location.href;
if (currentUrl) {
formsId = currentUrl.split('?formId=')[1];
} else {
return;
}
window.location = '/' + formsId;
debugger;
};
sforce.console.getEnclosingPrimaryTabId(focusDetailSubtabRedirect);
var focusDetailSubtabRedirect = function showTabIdRedirect(result) {
// window.onload = function showTabIdV1(result) {
//alert('2222');
var primaryTabID = result.id;
sforce.console.getSubtabIds(primaryTabID , showAllTabIdRedirect);
debugger;
}
var showAllTabIdRedirect = function showAllTabIdRedirect(result2) {
// alert('33333');
var firstSubTab = result2.ids[0];
sforce.console.refreshSubtabById(firstSubTab, false);
debugger;
//alert('Subtab IDs=====: ' + result.ids[0]);
};
window.onload = refreshDetailsTab;
</script>
You can check for successful completion of those methods. It's possible 'getSubtabIds' was at halt for some reason and that would cause the failure of calling the callback function 'showAllTabIdRedirect '.
See the documentation here for getSubtabIds
I think it has something to do with the window.location triggering first. It redirects the user before the other JS can load.

replacing and adding 3 different params to the url

I have a script that adds an param to the url when I click the assigned button - next click replaces it with a new param - this work great.
However - now I have three buttons - and I want each button to assign a param to the url - and replacing any params added by any of the other buttons. It also needs to be placed last behind the params that are already there.
so:
(button1) click3: /m4n?ecom-query=imac&seid=etailer-products&viewMode=3?param=grid
(button2) click4: /m4n?ecom-query=imac&seid=etailer-products&viewMode=3?param=list
(button3) click5: /m4n?ecom-query=imac&seid=etailer-products&viewMode=3?param=smalllist
The url before ?param is dynamic and can look different.
$('.click2').on('click', function() {
console.log("Clicked");
var url = window.location.pathname;
var url = window.location.href;
if (url.indexOf('?param=list') > -1) {
url = url.replace("?param=list", "") + '?param=grid'
} else {
url = url.replace("?param=grid", "") + '?param=list'
}
window.location.href = url;
});
How do I do this, I tried to modify my existing script but had no luck.
I think there is a small error in your approach:
All parameters in url should be connected with an &
so now your url should look like that
/m4n?ecom-query=imac&seid=etailer-products&viewMode=3&param=grid
now if you want to replace old pram, you need to remove the old value also. For that you can use regex as in following code
url = url.replace(/\&param=.*/,'') + '&param=list'
So the full code would be:
$('.click2').on('click', function() {
console.log("click2 Clicked");
var url = window.location.href;
url = url.replace(/\&param=.*/,'') + '&param=list';
window.location.href = url;
});
Hope it helps

Categories

Resources