debug help with rare unexpected output in js - javascript

I have the following javascript on my page that is supposed to generate and go to a url instead of posting a form:
var tokenList = ["auto", "usate"];
var dirList = [];
function makeUrl(prov, manuf, model, price){
if (_addToken(prov)){
_joinTokens();
}
if (_addToken(manuf)){
_addToken(model);
_joinTokens();
}
if (price){
return _joinDirs() + "?prezzo=" + price;
}
return _joinDirs();
}
function _addToken(tok){
if (tok){
tokenList.push(tok.replace(/ /g,"_"));
return true;
}
return false;
}
function _joinTokens(){
dirList.push(tokenList.join('-'));
tokenList = [];
}
function _joinDirs(){
if (tokenList){
_joinTokens();
}
var url = '/' + dirList.join('/');
if (url.charAt(url.length-1) == '/'){
url = url.slice(0, -1);
}
return url;
}
It's triggered by this code:
$(document).ready(function(){
$('#navForm').submit(function() {
var prov = $("[name=select-provincia]").val();
var manuf = $("[name=select-marca]").val();
var model = $("[name=select-modello]").val();
var price = $("[name=select-prezzo]").val();
var url = makeUrl(prov, manuf, model, price);
window.location = url;
return false;
});
});
It's been a long while since I translated this code from its original python. I've been getting rare errors in my server logs occasionally that show users trying to visit strange urls that look almost like two urls concatenated. I haven't been able to ever duplicate such an error, but my best guess is that there is something going on with my javascript. The last two times I got this error I noticed that the user was using firefox 3.6 and iphone. Could this be some kind of browser incompatibility? Is there anything wrong with my javascript at all? Is the error just in userland?
For reference here is an example wrong url:
/auto-usate-pesaro_e_urbino/fiat-500//rimini/fiat-500?prezzo=13000
and two possible correct ones:
/auto-usate-pesaro_e_urbino/fiat-500?prezzo=13000
/auto-usate-rimini/fiat-500?prezzo=13000
Any unrelated suggestions for optimizing the code are welcome since I am bad at this.

Not sure it that's the case, but I think those strange URLs might be a result of appending the generated URL to the URL of the page being viewed. You are generating just the pathname part of the URL, not including the protocol and host name (http://foo.com) -- it's possible that some browsers are interpreting this path as relative to the current one. Try prepending the URL with the protocol and hostname.
You might also want to see this answer: Setting JavaScript window.location and follow the advice to write the URL to window.location.href.

Related

Adding parameters to url on page load only if no paremeters already exist

I searched for the answer to my question and even tried some solutions, but wasn't able to get anything to really work. I'm newish to javascript, so that might also be why.
I have a specific URL and whenever someone goes to that URL, I want to add parameters to it, but only if no parameters are already present. Parameters get added to the URL for other on click events, but on page load, I need a set of parameters added to the URL.
I tried to use the history API and I think I'm kind of close, but I'm not able to get it to do what I want it to do.
function addDefaultParam(url) {
var currentURL = window.location.href; //get the current url
var baseURL = '/our-partners'; //this is the url that should have params added
var paramString = '?asc=true&sortBy=display_name'; //here are the params
if (currentURL === baseURL) {
window.history.pushState("object or string", "Title", "/" + paramString);
}
return url;
}
I'm using basic js in this because that's what was used in the other functions (I inherited this code). Any help would be greatly appreciated.
You can register the addDefaultParam function to fire when the document first loads in the browser and use the Location interface to check the state of the current path and query string of the URL and if they match your conditions, update the current query string value.
See below for an example:
window.addEventListener("load", addDefaultParam);
function addDefaultParam() {
let currentPath = document.location.pathname;
let currentQueryString = document.location.search;
let targetPath = "/our-partners";
if (currentPath === targetPath && !currentQueryString) {
document.location.search = "?asc=true&sortBy=display_name";
}
}

Is there a way to get Index HTML file name on default server location (Javascript or jQuery)

I'm trying to find a way to get the name of the current HTML file from URL (or any other possible way. It works most of the time, except for the case when the URL doesn't display the file name :
Works when : http://localhost:8080/Index.html
Doesn't work when : http://localhost:8080/ (hosting server will display index page that way on load).
The following function is the one I currently used. It is inspired from few other questions on StackOverflow talking about getting the filename from the complete URL.
function GetOtherLanguageLink(lang){
var pagename = window.location.pathname.substring(location.pathname.lastIndexOf("/") + 1);
pagename_split = pagename.split('.');
if (lang == "fr"){
return pagename_split[0] + "_en." + pagename_split[1];
}
else if (lang == "en"){
return pagename.replace("_en","");
}
else{
return pagename;
}
}
It is pretty simple, for Index.html it returns Index_en.html and vice versa.
When the URL doesn't have a filename, I get _en.undefined.
Is there some other way I could do that to get it work?
PS : if things are unclear, comment (I usually speak french so may not be clear).
Thanks in advance!

Proper way to check if a URL is the result of a createObjectURL call?

I have a situation where an image is being set by the user either to a URL or with bytes that is converted into a blob object URL. My understanding is that in order to prevent resource leaks, I should be freeing the blob object URLs when they are changed, but I'm not sure if I'm checking the type of the old URL correctly. Currently, the way I'm doing it is to just check if the url starts with 'blob:'. Here is a toy example function that demonstrates that it indeed seems to work:
var url;
for (i = 0; i < 5; i++) {
var oldurl = url;
console.log('i = ' + i)
if (i == 0 || i == 2 || i == 3) {
console.log('Switching to Object URL')
url = URL.createObjectURL(new Blob(new Uint8Array(0),
{type: 'image/png'}));
} else {
console.log('Switching to URL')
url = 'https://example.com/example-image.png';
}
if (oldurl && oldurl.startsWith('blob:')) {
console.log('Freeing old object url')
URL.revokeObjectURL(oldurl);
}
}
Is this the right way to do this? Is there a better way to do it?
I'll note that I've tried calling URL.revokeObjectURL on strings that are not object URLs and it seems to work fine, so it's also not clear to me how much it matters that I correctly determine whether the URL needs to be freed.
Note: This is a TypeScript script, but I think the question is equally valid in Javascript, so I've tagged with both.
You are right, i think that currently there is no other way at all.

JS: get hostname from url , regex not working

I am trying to get hostname from set of urls that my webapp can encounter with.
The desired output should be something like http://localhost/Webapp/, ending at /Webapp/ and everything after that should be removed.
Kindly note that I dont want to use word Webapp in regex as this name is dynamic and used for demo/testcase only.this can be anything , not harcoded.
In real example I am using location.href.replace(/index.+/g, "").replace(/#.+/g, "")
and I want to keep only hostname ending atWebapp/.
Problem:
my solution seems to working fine except "http://localhost/Webapp/#" is not working correctly ? why is that ? see fiddle below
JSFIDDLE: http://jsfiddle.net/bababalcksheep/um0uqb8v/
JS:
var getHost = function (url) {
return url.replace(/index.+/g, "").replace(/#.+/g, "")
};
var urls = [
"http://localhost/Webapp/",
"http://localhost/Webapp/#",
"http://localhost:8080/Webapp/#sdf#dfgdf#fdg",
"12.168.1.1:8080/Webapp/index.html#",
"https://localhost/Webapp/index.html#ab#bg",
"https://localhost/Webapp/index.html"
];
//Print all urls
$.each(urls, function () {
$("<p/>").text(getHost(this)).appendTo($(".test"));
});
Use url.match(/https?:\/\/([^\/]+)/);
EDIT:
It returns an array where the 1st element is the host with protocol and the 2nd without.
You can try removing anything after the last slash (files and hash-es):
var getHost = function (url) {
return url.replace(/\/[^/]*?$/, '/');
};
And here's the updated fiddle.
There's a bit of a trick you can use to get the browser to extract the hostname for you.
var getHost = function (url) {
var a = document.createElement('a');
a.href = url;
return a.hostname;
};
It also appears you want the path as well. You can access it with the pathname property of the a element. If you're doing that, you ought to rename the function to something like getHostAndPath().

How to obtain all the URLs generated dynamically in javascript menu?

I need to download all the images from the gallery of this site but I don't know how to obtain the URL of them or where these URL are stored on.
I tried to download the entire site with some programs but none of them seems to download even the menu.
Hope someone have any idea how to achieve this without having to do it manually one by one.
Here I can saw the code that produce the URLs:
<script type="text/javascript">
$(function(){
$(".text-frame").not(".default-frame").hide();
$('#menubar .button').hover(function(){
$(this).toggleClass("button-hover");
});
$('#menubar .button').click(function(){
$(".text-frame").hide();
$("#image-viewer").hide();
$(".button").removeClass("button-active");
var showTextframe = $(this).attr("rel");
$("#" + showTextframe).show();
$(this).addClass("button-active");
});
function showImages (imgLinks){
for (var i = 0; i < imgLinks.length; i++){
//$("#image-box").append($('<img>').attr('src', imgLinks[i]));
var $imgSelector = $('<a>'+ (i + 1) +'</a>')
.data('imglink',imgLinks[i])
.click(function(){
$("#image-box").find("img").attr('src', $(this).data('imglink'));
$("#image-links").find('a').removeClass('active');
$(this).addClass('active');
//alert ("I open Image" + $(this).data('imglink'));
});
$("#image-links").append($imgSelector);
$("#image-links").find('a:first').trigger('click');
}
}
$.get("plants_w_links.md", function(semillaMenu){
var markdownConverter = new Showdown.converter();
$semillaMenu = $(markdownConverter.makeHtml(semillaMenu));
$semillaMenu.find("img").each(function(){
var $menuimage = $(this);
var $menulink = $(this).parent("li").find("a");
var menuimages = $menulink.data("menuimages") || [];
menuimages.push($menuimage.attr("src"));
$menulink.data("menuimages",menuimages);
$menuimage.remove();
});
$semillaMenu.find("a").click(function(){
var menuImages = $(this).data("menuimages");
//$("#image-box").empty();
$("#image-links").empty();
if (menuImages){
$("#image-viewer").show();
showImages(menuImages);
}
});
$semillaMenu.addClass("sf-menu sf-vertical");
$('#semilla-menu').html($semillaMenu);
jQuery('ul.sf-menu').superfish({delay:10});
});
});
</script>
The function showImages seems to generate the URL but I don't know what to do with that.
I found here many question asking something similar but all of them talking about donwloading images with progressive URL (like blabla.com/image1.jpg, blabla.com/image2.jpg, etc.) but it is not the case, the images are generated without a pattern (or not any that I can obtain or deduce).
EDIT: I need to know how those functions work in order to run something similar in the Chrome inspect console that gives me all the URL instead the URL of the clicked option of the menu.
EDIT2: Someone in a IRC channel told me that the script may be jQuery, so I'm adding the tag.
var urls = new Array();
Array.prototype.forEach.call( document.images, function( img ){ urls.push( img.src ) } );
console.log( urls );
After execution these lines of code urls will contain sources of all images on the page.
Finally someone on the jQuery chat tell me how to solve my problem. Accesing directly to this link was the answer. The link seems to contain the structure of the menues that semillaMenu function format (aparently) and process to show the images on the site.
This doesn't solve my question yet, because it's only working for this case. What I wanted was a way to obtain the URLs with a script but it's solve my problem.
So I let it be unaswered if someone know how to make a script that gives all the image links without having to process manually the plants_w_links.md file.

Categories

Resources