I want to increment a url automatically using javascript and use it in Greasemonky on "Firefox"
ex:
www.google.com/id=1
www.google.com/id=01
www.google.com/id=001
www.google.com/id=0001
how can I achieve that using javascript???
here is what I wrote
var numberr = “2”;
var totall = “”;
var timeout = 12000;
setTimeout(function() {
var numm = “0” + numberr;
totall = “http://www.google.com/id=0” + numm;
window.location.href = totall;
}, timeout);
but i doesn't increment the zeros as i expected,
can anybody help me?
I don't know what is the problem, maybe it is the Greasemonkey?? I don't know
---------------------------------------------------------------
OK, It seems to be a javascript unfixable problem, So I'll implement the logic in a Windows application using C#, BUT I neet to know how to access [[firefox]] url , and reload action through C# in a windows application, can anybody help?????
Your variable values won't persist between page loads, thus resetting the counter each time. There is a solution, however!
GM_setValue(key, value);
GM_getValue(key[, defaultValue]);
http://diveintogreasemonkey.org/advanced/gm_getvalue.html
Alternatively, you can parse the current URL to determine your location within the loop. Try this:
// ==UserScript==
// #name Incremental URL
// #include http://www.google.com/*
// ==/UserScript==
var url = 'http://www.google.com/id=',
start = '2',
prepend = '0',
limit = 10,
timeout = 1000*12,
regex = new RegExp('^' + url + '(' + prepend + '{0,' + (limit-1) + '})' + start + '$');
matches = window.location.href.match(regex);
if(matches) {
setTimeout(function() {
window.location.href = url + prepend + matches[1] + start;
}, timeout);
}
What number are you coming up with? it looks like you are always going to be adding one more 0 than your description indicates since you are automatically adding one 0 with
var numm = “0” + numberr;
totall = “http://www.google.com/id=0” + numm;
by the look of those lines, even if you start out with "2", your first request will be
www.google.com/id=002
edit: and another thing, you are going to need to assign numm to numberrr at the end of the function call. Is this what you are trying to achieve?
var numberr = “2”;
var totall = “”;
var timeout = 12000;
setTimeout(function() {
var numm = “0” + numberr;
totall = “http://www.google.com/id=” + numm;
window.location.href = totall;
numberr = numm;
}, timeout);
edit again: ya, what Zed says, once you change your page location everything will reset anyways.
try this:
var numberr = “2”;
var totall = “”;
var timeout = 12000;
var numm;
setTimeout(function() {
numm += “0”;
totall = “http://www.google.com/id=0” + numm + numberr;
window.location.href = totall;
}, timeout);
var xcall = function()
{
this.url = "http://www.google.com/id=";
this.count = 0;
this.numberr = '1';
this.timeout = 12000;
};
xcall.prototype.ceros = function() {
var ret = "";
for(var x=0; x<this.count; x++){
ret += "0";
}
this.count++;
return ret;
};
xcall.prototype.sto = function() {
var locat = this.url + this.ceros() + this.numberr;
alert(locat);
//window.location.href = this.url + this.ceros + this.numberr;
};
var calls = new xcall();
setTimeout("calls.sto()", calls.timeout);
setTimeout("calls.sto()", calls.timeout);
Related
Here is the code...
I'm new to this. Thanks in advance for any advice!
<script type="text/javascript">
$(function () {
var url = "http://localhost:8888/wordpress_hattie/wp-content/uploads/2015/04/",
imgArray = [url+"paper_shape3.svg",
url+"mustard_shape2.svg",
url+"alt_shape.svg"],
randomNumber = Math.floor((Math.random() * imgArray.length)),
baseUrl = "url('" + imgArray[randomNumber] + "')";
$(".par_layer").css('background-image', baseUrl);
})();
</script>
You could store the index of the previously used image in localStorage and increment the index each time the script runs.
var basePath = 'http://localhost:8888/wordpress_hattie/wp-content/uploads/2015/04/';
var fileNames = ['paper_shape3.svg', 'mustard_shape2.svg', 'alt_shape.svg'];
var index = 0;
// Get last index from localStorage if present and increment it by 1.
if (localStorage.getItem('index') !== null) {
index = Number(localStorage.getItem('index')) + 1;
}
// Reset index to 0 if it exceeds the bounds of fileNames.
if (index >= fileNames.length) {
index = 0;
}
// Store index in localStorage for later use.
localStorage.setItem('index', index);
$('.par_layer').css('background-image', 'url(' + basePath + fileNames[index] + ')');
I would use cookies:
var r, m, i;
r = /(?:^|;)\s*i=([^;]+)/;
m = document.cookie.match(r);
i = m ? parseInt(m[1], 10) : 0;
console.log(i); // prints "0" then "1" then "2" then "0"...
document.cookie = "i=" + (++i % 3);
Alright dear poster, let's save your precious time:
<script type="text/javascript">
$(function () {
var url = "http://localhost:8888/wordpress_hattie/wp-content/uploads/2015/04/",
imgArray = [url+"paper_shape3.svg", url+"mustard_shape2.svg", url+"alt_shape.svg"],
r = /(?:^|;)\s*i=([^;]+)/,
m = document.cookie.match(r),
i = m ? parseInt(m[1], 10) : 0,
baseUrl = "url('" + imgArray[i] + "')";
$(".par_layer").css('background-image', baseUrl);
document.cookie = "i=" + (++i % imgArray.length);
})();
</script>
Side note: Won't work if cookies are disabled.
Pedantic note: Same for localStorage.
I made a function to add <a> tag in chat text and it worked fine, but it seems the variables of the function are shared between different instances of the function called from different chat rooms. I thought function variable were local, can anyone explain why I'm encountering this problem? Well I found out the code was wrong and a <p> tag the ajax function was adding to the string was interfering with this function. i fixed it by adding a space before the conflicting <p> tag and now it works fine...updated the code with english variable names too :)
function ajoutertagdelien(dataChat)
{
if (dataChat)
{
}
else
{
dataChat = " ";
}
var chatsendvar = dataChat;
var linkLocation, chatStringLeftPiece, chatfinal = "", chatStringRightPiece, lienfin, LinkAlone, LinktagString, LinkPiece;
var linkTagA = new Array();
var variablelocation = new Array();
var variablechatsend = new Array();
var increment=0;
var earlierLinkLength = 0;
linkLocation = chatsendvar.indexOf("www.");
while (linkLocation != -1) {
increment++;//
if (linkLocation != -1)
{
chatStringLeftPiece = chatsendvar.substring(0,linkLocation);
LinkPiece = chatsendvar.slice(linkLocation,chatsendvar.length);
lienfin = LinkPiece.indexOf(" ");
LinkAlone = LinkPiece.substring(0,lienfin);
chatStringRightPiece = chatsendvar.substring(((lienfin + linkLocation)),chatsendvar.length) ;
console.log( chatStringLeftPiece + " droit et gauche " + chatStringRightPiece + " number of theloop in the while=" + increment);
LinktagString = "<a target='_blank' href='http://"+ LinkAlone+"'>"+LinkAlone+"</a>";
chatsendvar = chatStringLeftPiece + " " + chatStringRightPiece;
linkTagA.push(LinktagString);
variablelocation.push(chatStringLeftPiece.length + earlierLinkLength);
earlierLinkLength = earlierLinkLength + LinktagString.length +1;
}
linkLocation = chatsendvar.indexOf("www.");
}
for (var x = 0, j = linkTagA.length; x<j; x++) {
chatsendvar = chatsendvar.split('');
chatsendvar.splice((variablelocation[x]),1," "+linkTagA[x]+" ");
chatsendvar = chatsendvar.join('');
};
return chatsendvar;
}
All this code to detect links in a text?
I know that's not what you asked, but this small function can do this. It can detect links beginning with www. or http:// and even handles url parameters, like ?a=1&b=2. Here is a demo fiddle.
The regex could be modified to handle https:// or url encoding for example, but you get my point.
function makeLinks(text) {
return text.replace(/(?:http:\/\/|(www\.))([\w\d.\/\?&=]+)/gi, '<a target="_blank" href="http://$1$2">$1$2</a>');
}
How can I check if URL contains variable or not? I have my function like this
My 2nd problem is, let says the URL already pass the lang variable, something like this (http://index.php?id=23&lang=en) i want that when they run this function again it will replace the lang variable to the new on instead of add new lang variable like this (http://index.php?id=23&lang=en&lang=jp)
function menu_goto(newvalue)
{
var baseurl = window.location.href ;
var langwithpara = "&lang=" + newvalue;
var langwopara = "?lang=" + newvalue;
if (newvalue != 0) {
if(baseurl.match(/?/)){
alert ('123');
location.href = baseurl + langwithpara ;
}
else{
alert ('456');
location.href = baseurl + langwopara ;
}
}
}
My new coding (work)
function menu_goto(newvalue)
{
var baseurl = window.location.href ;
var url = baseurl + ( (baseurl.match(/\?/))? '&':'?' ) + 'lang=' + newvalue;
location.href = url ;
}
window.location is actually an object, it has a 'search' property that make it easier to parse the query string.
function getParam(param){
var qs = window.location.search.substring(1).split('&');
var qsp;
for (p in qs){
qsp = qs[p].split('=');
if (qsp[0] == param) return qsp[1];
}
return null;
}
to check for a specific parameter :
var value = getParam('name');
the problem is probably the missing escaping of "?" in your RegExp:
if (baseurl.match(/\?/)) { // ...
a bit shorter would be:
var url = baseurl + ( (baseurl.match(/\?/))? '&':'?' ) + 'lang=' + newvalue;
You would probably want to clean any param "lang" before, so it doesn't become an array by multiple occurrence.
It would probably better to assemble the url anew like
function menu_goto(newvalue) {
var params = {};
if (self.location.search) {
var pairs = self.location.search.substring(1).split("&"); // skip the "?"
for (var i = 0; i < pairs.length; i++) {
var parts = pairs[i].split('=');
params[parts[0]] = parts[1];
}
}
params.lang = newvalue;
var query = new Array();
for (var p in params) query.push(p + '=' + params[p]);
var url = self.location.protocol + '//' + self.location.host + self.location.pathname
+ '?' + query.join('&');
self.location.href = url;
}
Here is yet another solution using RegExps:
function menu_goto2(newvalue) {
var url = self.location.href;
url = url.replace(/#.*/, ''); // clean any hash at end
url = url.replace(/[&\?]lang=[^&]*/, ''); // clean any param lang and its value
// we might have had two or more params and "lang" was the first one
// then we might have lost the "?" => replace first "&" by "?"
if (url.indexOf('?') < 0 && url.indexOf('&') >= 0) url = url.replace(/&/, '?');
url += ( url.match(/\?/)? '&':'?') + 'lang=' + newvalue; // add the new param lang
self.location.href = url;
}
Which could be shortened to
function menu_goto3(newvalue) {
var url = self.location.href.replace(/#.*/, '').replace(/[&\?]lang=[^&]*/, '');
if (url.indexOf('?') < 0 && url.indexOf('&') >= 0) url = url.replace(/&/, '?');
url += ( url.match(/\?/)? '&':'?') + 'lang=' + newvalue;
self.location.href = url;
}
You can simply use indexOf() method for this
if(window.location.href.indexOf("your value") != -1) {
alert("It contains");
}
else {
alert("Nope");
}
function menu_goto(newvalue)
{
var baseurl = window.location.href ;
var langwithpara = "&lang=" + newvalue;
var langwopara = "?lang=" + newvalue;
if (newvalue != 0) {
if(baseurl.match(/\?/)){ // change /?/ to /\?/
alert('123');
location.href = baseurl + langwithpara ;
}
else{
alert('456');
location.href = baseurl + langwopara ;
}
}
}
var openClose = $('.openClose');
openClose.on('click', function() {
var cook = ReadCookie('slideHide'),
miniParent = $(this).parent().parent().parent().children('.main-content'),
miniDisp = miniParent.css('display');
if (miniDisp ==="block") {
KillCookie('slideHide');
$(this).parent().parent().parent().children('.main-content').slideUp();
var slide = cook + "," + "#"+$(this)
.parent()
.parent()
.parent()
.parent().attr("id") +
" #"+$(this).parent()
.parent().parent().attr("id");
SetCookie('slideHide', slide, 100);
}
else
{
$(this).parent().parent().parent().children('.main-content').slideDown();
var newCookie=[];
var a= $('.module').children('.main-content').filter(":hidden");
for(var i=0;i<a.length;i++){
var d = $(a[i++]);
var c = "#"+d.parent('.module').attr('id');
}
newCookie= c;
console.log(newCookie);
KillCookie('slideHide');
SetCookie('slideHide',d, 100);
}
});
These are my cookie functions:
function SetCookie(cookieName,cookieValue,nDays) {
var today = new Date();
var expire = new Date();
if (nDays==null || nDays==0) nDays=1;
expire.setTime(today.getTime() + 3600000*24*nDays);
document.cookie = cookieName+"="+escape(cookieValue)
+ ";expires="+expire.toGMTString(),';path = /';
}
function KillCookie(cookieName) {
SetCookie(cookieName,"", - 1);
}
function ReadCookie(cookieName) {
var theCookie=""+document.cookie;
var ind=theCookie.indexOf(cookieName+"=");
if (ind==-1 || cookieName=="") return "";
var ind1=theCookie.indexOf(";",ind);
if (ind1==-1) ind1=theCookie.length;
return unescape(theCookie.substring(ind+cookieName.length+1,ind1));
}
Setting the cookie to make it slideUp and stay hidden works, but when I try to open it, it slidesDown, then I refresh the page it doesn't stay open like it should.
To sort of get the picture - http://jsfiddle.net/zRT9u/
If you need to know more please ask me I am willing to provide more!
I edited the javascript it almost works but I am not getting all the objects that I need
NEW EDIT- Tried the $.map() function but when I open one, and refresh all of them are now open?
else {
$(this).parent().parent().parent().children('.main-content').slideDown();
KillCookie('slideHide');
var newCookie=[];
var a= $('.module').children('.main-content').filter(":hidden");
var c = $.map(a,function(n,i){
return $(n).parent().attr('id');
});
newCookie= c;
SetCookie('slideHide',newCookie, 100);
}
Fixed it by using $.map and .join()
var openClose = $('.openClose');
openClose.on('click', function() {
var cook = ReadCookie('slideHide'),
miniParent = $(this).parent().parent().parent().children('.main-content'),
miniDisp = miniParent.css('display');
if (miniDisp ==="block") {
KillCookie('slideHide');
$(this).parent().parent().parent().children('.main-content').slideUp();
var slide = cook+","+ "#"+$(this).parent().parent().parent().attr("id");
SetCookie('slideHide', slide, 100);
} else {
$(this).parent().parent().parent().children('.main-content').slideDown();
KillCookie('slideHide');
var newCookie=[],
a= $('.module').children('.main-content').filter(":hidden"),
c = $.map(a,function(n,i){
return "#"+$(n).parent().attr('id');
});
newCookie= c.join(',');
SetCookie('slideHide',newCookie, 100);
}
});
By creating a "global" array and then using the $.map function as well as adding "#"+ to the map function I was able to get the actual ID names. Then I set newCookie to c.join(',') and everything works perfectly after that!
Let's say I have a url such as:
http://www.example.com/hello.png?w=100&h=100&bg=white
What I'd like to do is update the values of the w and h querystring, but leave the bg querystring intact, for example:
http://www.example.com/hello.png?w=200&h=200&bg=white
So what's the fastest most efficient way to read the querystring values (and they could be any set of querystring values, not just w, h, and bg), update a few or none of the values, and return the full url with the new querystring?
So:
Get the values of each querystring key
Update any number of the keys
Rebuild the url with the new values
Keep all of the other values which weren't updated
It will not have a standard set of known keys, it could change per URL
Simple solution
You can use URLSearchParams.set() like below:
var currentUrl = 'http://www.example.com/hello.png?w=100&h=100&bg=white';
var url = new URL(currentUrl);
url.searchParams.set("w", "200"); // setting your param
var newUrl = url.href;
console.log(newUrl);
Online demo (jsfiddle)
Get query string values this way and use $.param to rebuild query string
UPDATE:
This is an example, also check fiddle:
function getQueryVariable(url, variable) {
var query = url.substring(1);
var vars = query.split('&');
for (var i=0; i<vars.length; i++) {
var pair = vars[i].split('=');
if (pair[0] == variable) {
return pair[1];
}
}
return false;
}
var url = 'http://www.example.com/hello.png?w=100&h=100&bg=white';
var w = getQueryVariable(url, 'w');
var h = getQueryVariable(url, 'h');
var bg = getQueryVariable(url, 'bg');
// http://www.example.com/hello.png?w=200&h=200&bg=white
var params = { 'w':200, 'h':200, 'bg':bg };
var new_url = 'http://www.example.com/hello.png?' + jQuery.param(params);
You can change the function to use current url:
function getQueryVariable(variable) {
var query = window.location.search.substring(1);
var vars = query.split('&');
for (var i=0; i<vars.length; i++) {
var pair = vars[i].split('=');
if (pair[0] == variable) {
return pair[1];
}
}
return false;
}
//update URL Parameter
function updateURL(key,val){
var url = window.location.href;
var reExp = new RegExp("[\?|\&]"+key + "=[0-9a-zA-Z\_\+\-\|\.\,\;]*");
if(reExp.test(url)) {
// update
var reExp = new RegExp("[\?&]" + key + "=([^&#]*)");
var delimiter = reExp.exec(url)[0].charAt(0);
url = url.replace(reExp, delimiter + key + "=" + val);
} else {
// add
var newParam = key + "=" + val;
if(!url.indexOf('?')){url += '?';}
if(url.indexOf('#') > -1){
var urlparts = url.split('#');
url = urlparts[0] + "&" + newParam + (urlparts[1] ? "#" +urlparts[1] : '');
} else {
url += "&" + newParam;
}
}
window.history.pushState(null, document.title, url);
}
I like Ali's answer the best. I cleaned up the code into a function and thought I would share it to make someone else's life easier. Hope this helps someone.
function addParam(currentUrl,key,val) {
var url = new URL(currentUrl);
url.searchParams.set(key, val);
return url.href;
}
Another way (independent of jQuery or other libraries): https://github.com/Mikhus/jsurl
var u = new Url;
// or
var u = new Url('/some/path?foo=baz');
alert(u);
u.query.foo = 'bar';
alert(u);
My URL is like this: http://localhost/dentistryindia/admin/hospital/add_procedure?hid=241&hpr_id=12
var reExp = /hpr_id=\\d+/;
var url = window.location.href;
url = url.toString();
var hrpid = $("#category :selected").val(); //new value to replace hpr_id
var reExp = new RegExp("[\\?&]" + 'hpr_id' + "=([^&#]*)"),
delimeter = reExp.exec(url)[0].charAt(0),
newUrl = url.replace(reExp, delimeter + 'hpr_id' + "=" + hrpid);
window.location.href = newUrl;
This is how it worked for me.
Another way you you can do this, using some simple reg ex code by Samuel Santos here like this:
/*
* queryParameters -> handles the query string parameters
* queryString -> the query string without the fist '?' character
* re -> the regular expression
* m -> holds the string matching the regular expression
*/
var queryParameters = {}, queryString = location.search.substring(1),
re = /([^&=]+)=([^&]*)/g, m;
// Creates a map with the query string parameters
while (m = re.exec(queryString)) {
queryParameters[decodeURIComponent(m[1])] = decodeURIComponent(m[2]);
}
// Update w and h
queryParameters['w'] = 200;
queryParameters['h'] = 200;
Now you can either create a new URL:
var url = window.location.protocol + '//' + window.location.hostname + window.location.pathname;
// Build new Query String
var params = $.param(queryParameters);
if (params != '') {
url = url + '?' + params;
}
OR you could just use the params to cause browser to reload right away:
location.search = params;
OR do whatever you want with :)
You could do something like this:
// If key exists updates the value
if (location.href.indexOf('key=') > -1) {
location.href = location.href.replace('key=current_val', 'key=new_val');
// If not, append
} else {
location.href = location.href + '&key=new_val';
}
Regards
URI.js seems like the best approach to me
http://medialize.github.io/URI.js/
let uri = URI("http://test.com/foo.html").addQuery("a", "b");
// http://test.com/foo.html?a=b
uri.addQuery("c", 22);
// http://test.com/foo.html?a=b&c=22
uri.hash("h1");
// http://test.com/foo.html?a=b&c=22#h1
uri.hash("h2");
// http://test.com/foo.html?a=b&c=22#h2
Alright, If you are someone like me who only wants to update query string on URL without reloading the page. try following code
updateQueryString('id',post.id)
function updateQueryString(key, value) {
if (history.pushState) {
let searchParams = new URLSearchParams(window.location.search);
searchParams.set(key, value);
let newurl = window.location.protocol + "//" + window.location.host + window.location.pathname + '?' + searchParams.toString();
window.history.pushState({path: newurl}, '', newurl);
}
}
$('.desktopsortpriceHandler').on('change', function(){
let price_id = $(this).val()
$('.btn_product_locality_filter').attr("href", function (i, val) {
// if p is in between of url
val = val.replace(/p=.*?&/i, ""); ----> this will help to get the parameter using regex and replace it with ""
// if p at the end of url
val = val.replace(/&p=.*?$/i, ""); ----> this will help to get the parameter using regex and replace it with ""
return val + `&p=${encodeURIComponent(price_id.toString())}`; ---> then you can add it back as parameter with new value
});
})
i'm using this
function UpdateUrl(a,b,c,pagetitle) {
var url = window.location.href;
var usplit = url.split("?");
var uObj = { Title: pagetitle, Url: usplit[0] + "?w=a&h=b&bg=c};
history.pushState(uObj, uObj.Title, uObj.Url);
}