I have deployed a firebase site which works fine. The problem I have is the next:
Inside my main.js I have a variable called company. Is there a way to set that variable depending on the URL? For example:
site-ce207.firebaseapp.com/company=01
Or do you know another way?
As Mouser pointed out, this is invalid:
site-ce207.firebaseapp.com/company=01
However, this isnt:
site-ce207.firebaseapp.com#company=01&id=5
And it can be easily parsed:
var queries=location.hash.slice(1).split("&").map(el=>el.split("="));
Queries now.looks like this:
[
["company","01"],
["id","5"]
]
So to resolve it may do use an object:
var getQuery={};
queries.forEach(query=>getQuery[query[0]]=query[1]);
So now its easy to get a certain key:
console.log(getQuery["company"]);
Or new and more easy using a Map:
var query=new Map(queries);
console.log(query.get("company"));
I have a simple function I found a long time ago to handle this. I modified a bit to get the value by doing this.
function param(name) {
name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
results = regex.exec(location.search);
return results == null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}
and then to use the value I do the following
var myCity = param('cityid');
when issuing something like: http://example.com/?cityid=Guatemala
myCity will have the value of 'Guatemala' in my app.
Related
TL;DR: I am forced to use a javascript solution to store a URL parameter as a cookie, but when the function runs, it only stores the first 5 characters of the value I need.
I am working on implementing affiliate sales tracking across domains. As stated above, I need to store a value from a URL in a cookie so that I can pull it into a separate (functioning) script later. On my primary domain, I was able to do this with a simple .php script, but the third-party platform we use for our sales doesn't allow me to run .php scripts, so I found a javascript function that seemed to be working prior to today. That said, prior to today I was using test parameters that were only numerical (1234567890, etc.).
Here is an example of the kind of URL and parameter being used:
https://subdomain.platform-domain.com/subscribe/Product_ID?irclickid=QW6QnmxpdxySWmnwUx0Mo6bwUkEx5HXJxUUm0c0
This is the function I've been using successfully up until now:
function getParameterByName(name) {
name = name.replace(/[\[]/, '\\[').replace(/[\]]/, '\\]');
var regex = new RegExp('[\\?&]' + name + '=([^&#]*)'),
results = regex.exec(location.search);
return results === null
? ''
: decodeURIComponent(results[1].replace(/\+/g, ' '));
}
var results = getParameterByName('irclickid');
if (results != null || results != '') {
Cookies.set('irclickid', results, { expires: 30 });
}
For some reason, the function now only stores the first 5 characters of the value, or "QW6Qn" in this case. Any help or direction on how to make this work correctly is appreciated.
Resolution:
I found a function that was more apt for what I needed here on stackoverflow: How to get parameter name?, and replaced the first part of my javascript with the following, and it is now working as expected!
function getParameterByName(name, url) {
if (!url) url = window.location.href;
name = name.replace(/[\[\]]/g, "\\$&");
var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
results = regex.exec(url);
if (!results) return null;
if (!results[2]) return '';
return decodeURIComponent(results[2].replace(/\+/g, " "));
}
The last section remained the same:
var results = getParameterByName('irclickid');
if (results != null || results != '') {
Cookies.set('irclickid', results, { expires: 30 });
}
Thank you to those that offered help and insight.
const url = new URL('https://subdomain.platform-domain.com/subscribe/Product_ID?irclickid=QW6QnmxpdxySWmnwUx0Mo6bwUkEx5HXJxUUm0c0')
document.cookie = `irclickid=${url.searchParams.get('irclickid')}; expires=...`
You can see on https://caniuse.com/url if all required browsers support URL.
I have an object in JS like this:
var getToDoValue = document.getElementById("toDoInput").value;
var nameOfTeamMember = "Tobias";
var person = new Object();
person.task = "Task: " + getToDoValue;
person.member = "Member: " + nameOfTeamMember;
But problem comes when I try to enter the value of "nameOfTeamMember into an if statement:
var mem = person.member;
if (mem == "Tobias") {
console.log("works");
}
This does not work. But when I just console.log "var mem" outside of if statement it gives me "Member: Tobias". Any suggestions? Im still kinda new to JS so prob something with the comparisons
the issue with you code is that the value in person.member is "Member: Tobias" as you pointed out from the result of your console.log, which is the result from the line of code below where you are concatenating the name with the string "Memeber: " and assigning it to the member property.
person.member = "Member: " + nameOfTeamMember;
One option you could use to do the comparison would be:
if (mem.contains("Tobias", 8) {
console.log("works");
}
The 8 is so your search starts after the colon (:) so you don't include "Member:" in it, just what comes after it, which is the actual member name.
I'm using the JavaScript to create a cookie that will post the utm_source value="".
On the console I see the utm_source value, but not on the form
// Parse the URL
function getParameterByName(name) {
name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
results = regex.exec(location.search);
return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}
// Give the URL parameters variable names
var source = getParameterByName('utm_source');
// Set the cookies
if(Cookies.set('utm_source') == null || Cookies.set('utm_source') == "") {
Cookies.set('utm_source', source);
}
// Grab the cookie value and set the form field values
$(document).ready(function(){
$('input[name=utm_source').val(utm_source);
});
</script>
Problem 1
$('input[name=utm_source').val(utm_source);
The above line is causing problems for two reasons:
You're missing a closing bracket
utm_source is not defined anywhere (in the snippet you posted)
If you want to use the cookie value, you should do this:
$('input[name=utm_source]').val(Cookies.get('utm_source'));
Problem 2
On this line:
if(Cookies.set('utm_source') == null || Cookies.set('utm_source') == "") {
I think that you're mistakenly using .set() instead of .get() and that it could be simplified into this:
if(!Cookies.get('utm_source')) {
which would work because null and "" are both falsy values.
Thank you guys! Got it to work! Had to replace the name=customID
I'm hacking away at the react starter kit, and I came into a problem. I need javascript to get the query string from the url and display it in the document. I tried the following, but I get a location not defined. How can I do this in reacts and javascript?
function getParameterByName(name) {
name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
results = regex.exec(location.search);
return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}
#withStyles(styles)
class PlayerPage extends Component {
render() {
const title = 'Player';
var player = getParameterByName('player');
return (
<div className="PlayerPage">
<div className="PlayerPage-container">
<h1>{title}</h1>
<p>{player}</p>
</div>
</div>
);
}
}
The problem is that when your code runs in the server, location will not be defined because the node.js environment does not provide an implementation of location.
You may want to ensure that this component only renders on the client, or extract the route information from express request in server, rather than relying only on location.
I am trying to edit a Greasemonkey/jQuery script. I can't post the link here.
The code is obfuscated and compressed with minify.
It starts like this:
var _0x21e9 = ["\x67\x65\x74\x4D\x6F\x6E\x74\x68", "\x67\x65\x74\x55\x54\x43\x44\x61\x74\x65", ...
After "decoding" it, I got this:
var _0x21e9=["getMonth","getUTCDate","getFullYear", ...
It is a huge list (500+ ). Then, it has some variables like this:
month = date[_0x21e9[0]](), day = date[_0x21e9[1]](), ...
_0x21e9[0] is getMonth, _0x21e9[1] is getUTCDate, etc.
Is it possible to replace the square brackets with the actual variable name? How?
I have little knowledge in javascript/jQuery and can not "read" the code the way it is right now.
I just want to use some functions from this huge script and remove the others I do not need.
Update: I tried using jsbeautifier.org as suggested here and in the duplicated question but nothing changed, except the "indent".
It did not replace the array variables with the decoded names.
For example:
jsbeautifier still gives: month = date[_0x21e9[0]]().
But I need: month = date["getMonth"]().
None of the online deobfuscators seem to do this, How can I?
Is there a way for me to share the code with someone, at least part of it? I read I can not post pastebin, or similar here. I can not post it the full code here.
Here is another part of the code:
$(_0x21e9[8] + vid)[_0x21e9[18]]();
[8] is "." and [18] is "remove". Manually replacing it gives a strange result.
I haven't seen any online deobfuscator that does this yet, but the principle is simple.
Construct a text filter that parses the "key" array and then replaces each instance that that array is referenced, with the appropriate array value.
For example, suppose you have a file, evil.js that looks like this (AFTER you have run it though jsbeautifier.org with the Detect packers and obfuscators? and the Unescape printable chars... options set):
var _0xf17f = ["(", ")", 'div', "createElement", "id", "log", "console"];
var _0x41dcx3 = eval(_0xf17f[0] + '{id: 3}' + _0xf17f[1]);
var _0x41dcx4 = document[_0xf17f[3]](_0xf17f[2]);
var _0x41dcx5 = _0x41dcx3[_0xf17f[4]];
window[_0xf17f[6]][_0xf17f[5]](_0x41dcx5);
In that case, the "key" variable would be _0xf17f and the "key" array would be ["(", ")", ...].
The filter process would look like this:
Extract the key name using text processing on the js file. Result: _0xf17f
Extract the string src of the key array. Result:
keyArrayStr = '["(", ")", \'div\', "createElement", "id", "log", "console"]';
In javascript, we can then use .replace() to parse the rest of the JS src. Like so:
var keyArrayStr = '["(", ")", \'div\', "createElement", "id", "log", "console"]';
var restOfSrc = "var _0x41dcx3 = eval(_0xf17f[0] + '{id: 3}' + _0xf17f[1]);\n"
+ "var _0x41dcx4 = document[_0xf17f[3]](_0xf17f[2]);\n"
+ "var _0x41dcx5 = _0x41dcx3[_0xf17f[4]];\n"
+ "window[_0xf17f[6]][_0xf17f[5]](_0x41dcx5);\n"
;
var keyArray = eval (keyArrayStr);
//-- Note that `_0xf17f` is the key name we already determined.
var keyRegExp = /_0xf17f\s*\[\s*(\d+)\s*\]/g;
var deObsTxt = restOfSrc.replace (keyRegExp, function (matchStr, p1Str) {
return '"' + keyArray[ parseInt(p1Str, 10) ] + '"';
} );
console.log (deObsTxt);
if you run that code, you get:
var _0x41dcx3 = eval("(" + '{id: 3}' + ")");
var _0x41dcx4 = document["createElement"]("div");
var _0x41dcx5 = _0x41dcx3["id"];
window["console"]["log"](_0x41dcx5);
-- which is a bit easier to read/understand.
I've also created an online page that takes JS source and does all 3 remapping steps in a slightly more automated and robust manner. You can see it at:
jsbin.com/hazevo
(Note that that tool expects the source to start with the "key" variable declaration, like your code samples do)
#Brock Adams solution is brilliant, but there is a small bug: it doesn't take into account simple quoted vars.
Example:
var _0xbd34 = ["hello ", '"my" world'];
(function($) {
alert(_0xbd34[0] + _0xbd34[1])
});
If you try to decipher this example, it will result on this:
alert("hello " + ""my" world")
To resolve this, just edit the replacedSrc.replace into #Brock code:
replacedSrc = replacedSrc.replace (nameRegex, function (matchStr, p1Str) {
var quote = keyArry[parseInt (p1Str, 10)].indexOf('"')==-1? '"' : "'";
return quote + keyArry[ parseInt (p1Str, 10) ] + quote;
} );
Here you have a patched version.
for (var i = 0; i < _0x21e9.length; i++) {
var funcName = _0x21e9[i];
_0x21e9[funcName] = funcName;
}
this will add all the function names as keys to the array. allowing you to do
date[_0x21e9["getMonth"]]()