convert html into javascript string - javascript

I'm getting some html from node-request and I want to place that html into my javascript code as strings:
<div id='frontpage'><div set-href="'/user/' + (user | encodeURIComponent)">userlink</div></div>
The goal is to get an output like this for angularjs:
var createCache = function (path, template) {
return "\n $templateCache.put('" + path + "',\n '" +template + "'\n );\n";
}
This code is too naive, there are issues with quotes and other potential problems. How could it be done correctly? Is there a way to get the string from node-request itself? Thanks.

Related

GoogleTagManager do not seem to accept base64 encoded picture

Is it me or GoogleTagManager do not seem to accept base64 encoded pictures?
Exemple with the very basic code below with a very basic image.
I get the following error :
- Type : JavaScript Too Long"
- Description :
"The JavaScript in your Arbitrary HTML tag has too many contiguous non-whitespace characters (e.g. an array literal '[1,2,..]' that is too long). Try inserting spaces between statements to allow compilation (e.g. change '[1,2,...]' to '[1, 2, ...]')."
Is there no way to implement this in GTM, beside putting the js somewhere else than directly into GTM?
Best,
J.
<script type="text/javascript">
var myurl = "http://wwww.toto.com";
var myimg = "data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQH/2wBDAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQH/wAARCACYAMoDASIAAhEBAxEB/8QAGgABAQEBAQEBAAAAAAAAAAAAAAoJCAUHBv/EACoQAAEEAgMBAAECBwEBAAAAAAAEBQYHAwgBAgkKFBE5EhMVIXi3uHR1/8QAGAEBAAMBAAAAAAAAAAAAAAAAAAMEBQb/xAAhEQACAwEAAgMBAQEAAAAAAAACAwABBAUSEwYRIRQjMf/aAAwDAQACEQMRAD8Av4AAiAAIgACIAAiAAIgACIAAiAAIgACIAAiAAIgACIAAiAAIgACIAAiAAIgACIAAiAAIgACIAAiAAIgACIAAiAAIgACIAAiAAIgACIAAiAAIgACIAAi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AEQABEAARAAEQABEAARAAEQABEAARAAEQABEAARAAEQABEAARAAEQABEAARAAEQABEAARAAEQABEAARAAEQABEAARAAEQABEAARAAEQABEAARAAEQABEAARAAEQABEAARAAEQABEAARAAEQABEAARAAEQABEAARAAEQABEAARP/Z";
$("#beta-ad").empty();
$('<div/>', { id: "1" }).insertBefore($("#beta-ad"));
$("#1").append('<img src="' + myimg + '" style="display:inline; width: auto;" ></img>')
</script>
I think this is by design. But the workaround proposed by #Matus works.
To get around the issue of having to generate JS for a very long base base 64 encoded string I wrote a utility function, splitting the string into chunks of 150 (which GTM accepts), and generating the JS concatenation code.
You can then drop this code into your GTM tag, and reference the base64 variable.
function splitString(string, size, multiline) {
var matchAllToken = (multiline == true) ? '[^]' : '.';
var re = new RegExp(matchAllToken + '{1,' + size + '}', 'g');
var responses = string.match(re);
var value = "var base64='';";
responses.forEach(response => {
value += "base64+='" + response + "';";
});
return value;
}
var base64 = 'eyJ3aWRnZXRfc2.... etc';
var gtmString = splitString(base64, 150, true);
console.log(gtmString);
http://jsfiddle.net/azqpdwxg/2/

Replace array-mapped variables with the actual variable name/string?

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"]]()

What is arbitrary data/JSON?

I've recently come across the term arbitrary data/ arbitrary json and i can't seem to understand what exactly is it and/or find any documentation on it. I know that JSON is a format for sending data over the internet, so how exactly can a format be arbitrary?
EDIT::
//more code
var buildItem = function(item) {
var title = item.name,
args = [],
output = '<li>';
if (item.type == 'method' || !item.type) {
if (item.signatures[0].params) {
$.each(item.signatures[0].params, function(index, val) {
args.push(val.name);
});
}
title = (/^jQuery|deferred/).test(title) ? title : '.' + title;
title += '(' + args.join(', ') + ')';
} else if (item.type == 'selector') {
title += ' selector';
}
output += '<h3>' + title + '</h3>';
output += '<div>' + item.desc + '</div>';
output += '</li>';
return output;
};
//more code
in the example code above, i am told that the .params is arbitrary data from a JSON request [for the jQuery API documentation].
What then is arbitrary data?
Would really appreciate any answers and/or clarifications.
jsFiddle: http://jsfiddle.net/QPR4Z/2/
Thanks!
arbitrary |ˈärbiˌtrerē|
adjective
based on random choice or personal whim, rather than any reason or
system: his mealtimes were entirely arbitrary.
Mathematics: (of a constant or other quantity) of unspecified value.
It just means there could be any value in there. This is opposed to a specification that says something like "this array always contains X, Y and Z". Arbitrary values in contrast say "we're sending you something in this array, but we can't really tell you in advance what exactly that is." If you're told that you can send arbitrary data yourself, it means you can send anything you want, it doesn't have to follow any particular format.
Note that this is all about the data contained in the JSON format, not about the JSON format itself.
It means "Some organisation of the data structure (including names of properties) that was just made up by some person" rather than being an established standard.
The data structure is arbitrary. It is expressed in the JSON standard (which isn't).

Unexpected Token Illegal with onclick Java Script in Salesforce.com

I have been working on this most of the morning but to no end. I am trying to execute a button that uses OnClick Java in Salesforce.com and it keeps throwing errors. I think the issue may be with special characters in the data as it works when I simply use just text. But any time numbers or any special characters are present I get the error "unexpected token ILLEGAL". Can anyone help me to see what I am doing wrong and how I can get away from failing when special characters are involved?
{!REQUIRESCRIPT("/soap/ajax/28.0/connection.js")}
var opptyObj = new sforce.SObject("Opportunity");
var caseObj = new sforce.SObject("Case");
var today = new Date();
var sOpptyId = "{!Case.Opportunity__c}";
if( sOpptyId != "")
{
alert("This case is already tied to an opportunity!");
}
else
{
opptyObj.AccountId = "{!Case.AccountId}";
opptyObj.CloseDate = sforce.internal.dateTimeToString(today);
opptyObj.Description="{!Case.Description}";
opptyObj.Case__c = "{!Case.Id}";
opptyObj.Name = "{!Case.Subject}";
opptyObj.StageName = "Estimate in Progress";
opptyObj.Created_from_Case__c = "Y";
opptyObj.Type = "New Business";
opptyObj.Amount = ".01";
var opptyresult = sforce.connection.create([opptyObj]);
if (opptyresult[0].success=='false')
{
alert("Opportunity creation failed: " + opptyresult[0].errors.message);
}
else
{
caseObj.Id = '{!Case.Id}';
caseObj.Opportunity__c = opptyresult[0].id;
caseObj.Status = "Estimate in Progress";
var caseResult = sforce.connection.update([caseObj]);
if(caseResult[0].success == 'false')
{
alert("Case update failed: " + caseResult[0].errors.message);
}
else
{
alert("An opportunity has been created and linked to this case.");
location.reload(true);
}
}
}
Assuming this is some kind of template, whatever is rendering this needs to properly escape some values in the strings it's inserting.
Given this:
opptyObj.Description="{!Case.Description}";
Let's say I enter a description consisting of this:
"That is awesome," said John.
When that is rendered in your template the result is this:
opptyObj.Description=""That is awesome," said John.";
As you might be able to see, the result is a syntax error.
You need to escape quote characters in an text inserted this way. And without knowing what is technology rendering this template I can't give you any specifics, but you want to replace " with \" and ' with \'. The \ escapes characters, forcing them to be treated as literal characters in the string instead of other special meaning.
This must be done as it's being inserted into the script. Something in the spirit of this:
opptyObj.Description="{!Case.Description.replace(/'/, "\\'").replace(/"/, '\\"')}
Exactly how to do that depends on what language or template engine is being used here. But th eresult should look like this:
opptyObj.Description="\"That is awesome,\" said John.";
Ruby on Rails implements an escape_javascript method, which sanitizes data for injection into Javascript. It does the following replacements. It seems like a good baseline.
'\\' => '\\\\'
'</' => '<\/'
"\r\n" => '\n'
"\n" => '\n'
"\r" => '\n'
'"' => '\\"'
"'" => "\\'"
UPDATE:
According to this: http://www.salesforce.com/us/developer/docs/pages/Content/pages_security_tips_scontrols.htm
It looks like you want the JSENCODE function. Something like this, perhaps?
opptyObj.Description="{!JSENCODE(Case.Description)}";

jQuery - parsing JSON data - Having trouble with variable name

My first delve into working with JSON data. I have a bit of experience using jQuery though.
I'm posting to this URL (tumblr api): jyoseph.com/api/read/json
What I'm trying to do is output the json that gets returned. What I have so far:
$(document).ready(function(){
$.getJSON("http://jyoseph.com/api/read/json?callback=?",
function(data) {
//console.log(data);
console.log(data.posts);
$.each(data.posts, function(i,posts){
var id = this.id;
var type = this.type;
var date = this.date;
var url = this.url;
var photo500 = this.photo-url-500;
$('ul').append('<li> ' +id+ ' - ' +type+ ' - ' +date+ ' - ' +url+ ' - ' +photo500+ ' - ' + ' </li>');
});
});
});
See my jsbin post for the entire script: http://jsbin.com/utaju/edit
Some of the keys from tumblr have "-" hyphens in them, and that seem to be causing a problem. As you can see "photo-url-500" or another "photo-caption" is causing the script to break, it's outputting NaN.
Is there a problem with having hyphens in the key names? Or am I going about this all wrong?
If there are dashes in the names you'll need to access them differently. Change var photo500 = this.photo-url-500; to read var photo500 = this["photo-url-500"];.
Please note it is best not to append inside each iteration. Better to append to a string or push to an array then append once after the iterator has finished. Appending to the dom is expensive.
Use the bracket notation to access the members:
var photo500 = this['photo-url-500'];

Categories

Resources