js ecwid url redirect - javascript

I have been trying to set up redirects for a range of ecwid urls starting from /shop to /shop#!/~/ to lead to /shop#!/~/cart
I have come up with this code:
var wrong_url = ['http://example.com/shop','http://example.com/shop#','http://example.com/shop#!','http://example.com/shop#!/','http://example.com/shop#!/~','http://example.com/shop#!/~/'];
var current_url = document.URL;
for (i=0;i<wrong_url.length;i++) {
if (current_url==wrong_url[i]) {
document.location.replace('http://example.com/shop#!/~/cart');
break;
}
}
It works all right but there is a problem. When I am at /shop#!/~/cart and then manually change url to, say, /shop#!/~/ it won't get redirected until I refresh the page. I believe this has something to do with ajax behavior of ecwid shopping cart but can't figure out how to fight it.
Need help?

Vitaly from Ecwid here.
The issue in the current version of your script is that it doesn't detect the changes to the URL like you described.
So you will need to create a handler for such situations separately. For example, you can do it like this:
<script>
var wrong_url = ['http://example.com/shop','http://example.com/shop#','http://example.com/shop#!','http://example.com/shop#!/','http://example.com/shop#!/~','http://example.com/shop#!/~/'];
var current_url = document.URL;
// function to check current URL and make a redirect
function checkUrl(){
for (i=0;i<wrong_url.length;i++) {
if (current_url==wrong_url[i]) {
document.location.replace('http://example.com/shop#!/~/cart');
break;
}
}
}
// Execute checkUrl() function each time URL is changed
$(window).bind('hashchange', function() {
checkUrl();
});
// Execute checkUrl() function on initial page load
checkUrl();
</script>

Related

how can I redirect first timers on the website to the signup page?

Ok so basicly here is my script:
window.onload = () => {
`enter code here` if (**first_time**) {
window.location.href = "www.netlify.app/teamadventures.signup";
}
}
I want to make it so that if it's your first time on the website you get taken to a signup page automatically. How do I do this with vanilla JS?
You can use cookies or localStorage for that. The localStorage is the easiest method. First check if there is something stored on it with getItem. If not, store this information (the user visited the page) in localStorage with setItem and redirect the page to the Sign Up.
var first_time = localStorage.getItem("first_time");
if (!first_time){
localStorage.setItem("first_time", 1);
window.location.href = "www.netlify.app/teamadventures.signup";
}

How can I trigger this function from the URL?

I have this Javascript on my homepage which opens a popup.
I need a way to create a URL which then opens the popup immediately.
I've read on other posts that I need to use parameters and then add something like ?parameter=true to the url. The problem is I don't know javascript.
Can anyone help me with adding parameters to my js code?
jQuery(document).ready(function() {
$("#customButton").click(function () { $("#crazyrocket-launch-icon").trigger("click") });
});
You can use searchParams.Get() to grab the value of the parameter from the URL. You can then run your function on document ready after checking with an if statement.
var url_string = "http://www.example.com/t.html?popup=true";
var url = new URL(url_string);
var popup = url.searchParams.get("popup");
jQuery(document).ready(function() {
if (popup) {
$("#crazyrocket-launch-icon").trigger("click");
}
});

Attempting window.location or window.location.href redirect which is causing a loop

I'm attempting to use javascript to determine if the user is using a certain language and if they're not using english then for the page to load a different page BUT with the params of which I've grabbed from the url.
I have been able to load the page with the params but I keep falling into a loop reloading the page, even after skimming through the countless other examples, such as: this or this.
function locateUserLanguage() {
var languageValue = (navigator.languages ? navigator.languages[0] : (navigator.language || navigator.userLanguage)).split('-');
var url = window.location.href.split('?');
var baseUrl = url[0];
var urlParams = url[1];
if (languageValue[0] === 'en') {
console.log('no redirect needed, stay here.');
} else {
// I tried to set location into a variable but also wasn't working.
// var newURL = window.location.href.replace(window.location.href, 'https://www.mysite.dog/?' + urlParams);
window.location.href = 'https://www.mysite.dog/?' + urlParams
}
} locateUserLanguage();
I've attempted to place a return true; as well as return false; but neither stop the loop.
I've tried window.location.replace(); and setting the window.location.href straight to what I need, but it's continuing to loop.
There is a possibility that the script in which this function is written is executed in both of your pages (english and non-english) on load. So, as soon as the page is loaded, locateUserLanguage function is executed in both english and non-english website causing the infinite loop.
You need to put a check before you call locateUserLanguage function.
Suppose english website has url = "www.myside.com" and non-english website has url "www.myside.aus". So the condition needs to be
if (window.location.host === "www.myside.com") { locateUserLanguage() }
This will make sure that locateUserLanguage is called only in english website.
Or other apporach can be to load this script only in english website which will avoid the usage of conditional statement.
Hope it helps. Revert for any doubts.

Execute a function after changing location.href

I want to call a function after redirecting the page.
Inside my function I put a parameter which is an ID but when I check the console it wont display. I know I can be able to run it via on click event but I wont get the ID param from the previous page.
Is there a way to get it done?
Code:
function encode(item_id){
$('.js-encode').click(function(){
var url = $(this).data('url');
location.href = url; // new url
save(item_id); // call function after new url finish loading
});
}
function save(item_id){
console.log(item_id); // check if there's item_id exists
}
I agree with Katana's comment. Anything after your redirect statement will not run because the page itself is redirecting. One way that I would suggest to still get the item_id and get around that barrier, would be to include the item_id in the redirect url as a parameter. Then once on the new page, parse that parameter out of the url and save the item_id.
A great example from Cory Laviska's article on Parsing URLs in Javascript, shows how you can get the individual parameters from a URL.
Building onto Manish' answer:
Function on the current page:
function encode(item_id){
$('.js-encode').click(function(){
var url = $(this).data('url');
location.href = url+'?saved_item_id='+item_id; // new url
});
}
Function on the REDIRECTED Page (assuming you only have one parameter)
$( document ).ready(function() {
var url = $(this).data('url');
var item_id = url.queryKey['saved_item_id'];
save(item_id);
});
It may need a few tweeks because I didn't test the code, but hopefully it'll get you on the right track. :)
Hopefully this helps. If it helps and/or answers your question, please select as answer and up vote! :D Feel free to let me know if you have any questions
Try this one
The container is the section of your page where you perform an action.
function encode(item_id){
$('.js-encode').click(function(){
var url = $(this).data('url');
$("#container").load(url,function(){
// other stuffs and functionalities
save(item_id); // call function after new url finish loading
});
});
}
You can try something like this.
function encode(item_id){
$('.js-encode').click(function(){
var url = $(this).data('url');
location.href = url+'?saved_item_id='+item_id; // new url
//save(item_id); // call function after new url finish loading
});
}
/*(function save(item_id){
console.log(item_id); // check if there's item_id exists
}*/
Further more , On New redirected URL you can get item_id which was appended to URL in previous page.
Hope this may help.

How can I execute a script after calling window.location.href?

I have a script that redirects the user to another page. I want to load some content into a div on the new page after the new page has fully loaded. How can I do this. The following doesn't work.
function goToPage() {
window.location.href = 'http://www.mypage.com/info';
$('.my_class').load('my/url/path/with/content/to/load');
}
The newly loaded page http://www.mypage.com/info contains the following div:
<div class="my_class"></div>
What am I doing wrong?
Redirect to the new page, but append a hash signal to the URL.
function goToPage() {
window.location.href = 'http://www.mypage.com/info#load-stuff;
}
Then on load of the target page, evaluate the URL checking for that hash signal.
function pageLoad() {
if (window.location.hash === "#load-stuff") {
$('.my_class').load('my/url/path/with/content/to/load');
}
}
If your application is using jQuery it'd look something like:
$(function () {
if (window.location.hash === "#load-stuff") {
$('.my_class').load('my/url/path/with/content/to/load');
}
});
That's the rough idea at least.
As pointed out in the other answers, you won't be able to perform any script instructions from your original site. Instead of using PHP to create the content statically, you could also use HTML fragments as arguments, e.g. like this:
// in the original page:
function goToPage() {
window.location.href = 'http://www.mypage.com/info#my/url/path/with/content/to/load';
}
// in http://www.mypage.com/info:
$( document ).ready(function () {
if(window.location.hash)
$('.my_class').load(window.location.hash.substring(1));
}
An easy way to pass data to your page you are redirecting to would be to set some url parameters.
For example:
window.location.href - "http://youpage.com/?key=value"
When that page loads you could have a:
$(document).ready(function(){
var my_param = getUrlParameter('key');
if(my_param == "value"){
//do your stuff here
}
});
var getUrlParameter = function getUrlParameter(sParam) {
var sPageURL = decodeURIComponent(window.location.search.substring(1)),
sURLVariables = sPageURL.split('&'),
sParameterName,
i;
for (i = 0; i < sURLVariables.length; i++) {
sParameterName = sURLVariables[i].split('=');
if (sParameterName[0] === sParam) {
return sParameterName[1] === undefined ? true : sParameterName[1];
}
}
};
You should just run
$('.my_class').load('my/url/path/with/content/to/load');
on this page: http://www.mypage.com/info.
When you do window.location.href = 'http://www.mypage.com/info'; you're redirecting to another page. Nothing after that line will happen. You have to instead run the code after that line on the page that's loaded.
You can do this a few different ways. Try leveraging the localstorage API and passing info or content with a name and value pair (or a few of them) and unpack it on the receiving end.
On the page you're redirecting to, check for the localstorage key, and then load the contents of it (the aforementioned name and value pairs) into a div.
As an alternative, you can write one script file that you can deploy to several pages; do a check on window.location.href and conditionally load script accordingly. If you're on the redirected page, you can run whatever script you like. The nice part about doing it this way is that you're still working with one JS file - no need to fragment your code (assuming, of course, that the pages you're working with are all on the same site).
You don't need to do anything with php if you don't want to, or hashes... there's a few nifty tools that will do the trick if you can leverage HTML5 and its associated APIs.
window.location = '#/MyPage';
setTimeout(function() {
//MyCode To Run After PageLoad
});
You are redirecting the browser with window.location.href and I'm afraid as you are purely just changing the browser's location, you can't have any affect/input on the page you are moving to (unless you use query string parameters and then create content with something like PHP (myurl.php?newcontent=whatever) )
Once you redirect you can no longer execute scripts on that page, as the page is unloaded.
Try this,
redirect page:
function goToPage() {
window.location.href = 'http://www.mypage.com/info;
}
mypage.com/info:
js:
$('.my_class').load('my/url/path/with/content/to/load');
html:
<div class="my_class"></div>
I hope this helped you out, and let me know if you need further assistance!

Categories

Resources