have to encode by HTML link with base64 - javascript

It is my first post and hope it won't be already solved previously.
I'm using a call center software and also using Salesforce lightning.
When a caller calls, I would like to check in my CRM if it is a customer or not.
It was possible easily with the basic version of Salesforce but is not anymore because the link is coded with base64.
Please, read this post for more explanation : https://tomsmalara.blogspot.com/2019/01/create-lightning-component-that.html
So, I have to create a HTML page for collecting the caller phone number and compose + encrypt the Salesforce link and open the link encrypted.
<!DOCTYPE html>
<html>
<head>
<title>Waiting a call ...</title>
<style>
body {text-align: center;}
</style>
</head>
<body>
<form name="form1" onsubmit="event.preventDefault();return displayResult();">
<label for="name">Phone number:</label>
<input type="text" id="PhoneNumber" name="PhoneNumber" size="10">
<div id="myEncoding"></div>
</form>
<script>
function b64EncodeUnicode(PhoneNumber) {
// first we use encodeURIComponent to get percent-encoded UTF-8,
// then we convert the percent encodings into raw bytes which
// can be fed into btoa.
var Mytxt = '{"componentDef":"forceSearch:search","attributes":{"term":"'+PhoneNumber+'","scopeMap":{"resultsCmp":"forceSearch:resultsTopResults","label":"Top Results","type":"TOP_RESULTS","cacheable":"Y","id":"TOP_RESULTS","labelPlural":"Top Results"},"context":{"disableSpellCorrection":false,"SEARCH_ACTIVITY":{"term":1234567890}}},"state":{}}';
return btoa(encodeURIComponent(Mytxt).replace(/%([0-9A-F]{2})/g,
function toSolidBytes(match, p1) {
var MyResult = String.fromCharCode('0x' + p1);
return MyResult;
}));
}
function displayResult() {
var result = b64EncodeUnicode(PhoneNumber);
document.getElementById('myEncoding').innerHTML = result;
return false;
window.open("https://mycompany.lightning.force.com/one/one.app#" +result,,,true)
}
</script>
</body>
</html>
Something is wrong and tried different things without result.
I will really appreciate if someone can find what is wrong and explain it to me
Thank you in advance

PLease find the solution I found to remove the input steps ...
<!DOCTYPE html>
<html>
<head>
<title>Waiting a call ...</title>
<style>
body {text-align: center;}
</style>
</head>
<body onload=acceptParam()>
Waiting a call ...
<script>
function acceptParam(){
var hashParams = window.location.href.substr(1).split('?'); // substr(1) to remove the `#`
hashParams = hashParams[1].split('&');
var p = hashParams[0].split('=');
//document.getElementById('PhoneNumber').value = p[1] // Pour info
var stringToEncode = '{"componentDef":"forceSearch:searchPage","attributes":{"term":"'+p[1]+'","scopeMap":{"type":"TOP_RESULTS"},"context":{"disableSpellCorrection":false,"disableIntentQuery":false,"permsAndPrefs":{"SearchUi.searchUIPilotFeatureEnabled":false,"SearchExperience.LeftNavEnhancementEnabled":true,"Search.crossObjectsAutoSuggestEnabled":true,"SearchResultsLVM.lvmEnabledForSearchResultsOn":true,"MySearch.userCanHaveMySearchBestResult":false,"SearchResultsLVM.lvmEnabledForTopResults":false,"OrgPermissions.UnionAppNavSmartScope":false,"SearchUi.feedbackComponentEnabled":false,"SearchExperience.TopResultsSingleSOSLEnabled":false,"OrgPreferences.ChatterEnabled":true,"Search.maskSearchInfoInLogs":false,"SearchUi.orgHasAccessToSearchTermHistory":false,"SearchUi.searchUIInteractionLoggingEnabled":false,"MySearch.userCanHaveMySearch":false},"searchDialogSessionId":"bdded2dc-91d1-3b3e-11d7-ff339bce1727","searchSource":"INPUT_DESKTOP"},"groupId":"DEFAULT"},"state":{}}'
var encoded = window.btoa(stringToEncode);
//var output = "Encoded String : " + encoded;
//document.getElementById("myEncoding").innerHTML = "Original String: " + p[1] + "<br>" + output;
window.location.assign("https://mycompany.lightning.force.com/lightning/one/one.app?source=alohaHeader#"+encoded);
}
</script>
</body>
</html>
PLease, can you say me what do you think about it ? Maybe we can be more efficient ?

Related

Google Apps Script: passing error into templated HTML

I have the following code:
code.gs:
function onOpen() {
var ui = SpreadsheetApp.getUi();
ui.createMenu('My Menu')
.addItem('Test', 'showTestForm')
.addToUi();
}
function showTestForm() {
var html = HtmlService.createHtmlOutputFromFile('TestForm');
SpreadsheetApp.getUi().showModalDialog(html, 'TEST');
}
function Test(formObject){
Logger.log("TEST")
var a = new Error( "Allready present "+ formObject);
a.error_code = 99;
Logger.log(JSON.stringify(a));
throw a;
}
TestForm.html
<!DOCTYPE html>
<html lang="ru">
<head>
<meta charset="UTF-8" />
<base target="_top">
<script>
function onFailure(error) {
var keys = Object.keys(error);
alert(JSON.stringify(keys));
alert(JSON.stringify(error.message));
alert(JSON.stringify(error.error_code));
}
function onSuccess() {
alert("Success");
}
</script>
</head>
<body>
<input type="submit" value="Save" onclick="google.script.run.withFailureHandler(onFailure).withSuccessHandler(onSuccess).Test('1')" />
<input type="button" value="Close" onclick="google.script.host.close()" />
</body>
</html>
When I open TestForm from menu and press "Save" I've got following log from Logger:
[18-12-24 23:08:24:765 PST] TEST
[18-12-24 23:08:24:766 PST] {"message":"Allready present 1","error_code":99}
So I see, that error object have properties 'message' and 'error_code'. But in browser I've got following alerts:
["name"]
"Error: Allready present 1"
undefined
So I see, that recived error object has only one empty (i've checked) property "name". But if I but refer to the property "message, I've got string like in original object (but not the same). And it looks like that object haven't poperty "error_code".
What's the matter?
I thought you might like a complete working example as I know this stuff can be quite frustrating.
This a simple example templated HTML file that can be used as a dialog or a webapp. All it does is create a Google Doc file with todays date in the header and footer of each page and it puts the file into the same directory as the spreadsheet which contains the script. That's it. I use the Chrome Browser. I don't even care if my scripts won't run on another browser.
Here's the HTML: (FileName:'docwithdate.html')
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<?!= include('resources') ?>
<?!= include('css') ?>
</head>
<body>
<?!= include('form') ?>
<?!= include('script') ?>
</body>
</html>
The Resources: (FileName: 'resources.html')
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
The CSS: (FileName: 'css.html')
<style>
body {background-color:#ffffff;}
input[type="button"]{padding:0 0 2px 0;}
</style>
The Form: (FileName: form.html) This is probably push the templating idea a little far.
<form id="myForm" onsubmit="event.preventDefault();processForm(this);" >
<input type="text" id="txt1" name="filename" />
<input id="btn" type="submit" value="Submit" />
</form>
The Javascript: [FileName: 'script.html')
<script>
function createFile(){
var name=document.getElementById('filename').value;
google.script.run
.withSuccessHandler(function(rObj){
var html='<br />Go To File:' + rObj.filename + '';
$(html).appendTo("body");
})
.createTemplatedGoogleDoc(name);
}
function getInputObject(obj) {//I'm probably doing something wrong here. But this is what I had to do to get the object with the properties that I desired. So if you have another way. Go for it.
var rObj={};
for(var i=0;i<Object.keys(obj).length;i++){
if(obj[i].type=="text"){
rObj[obj[i].name]=obj[i].value;
}
console.log('Object.keys(rObj): %s',Object.keys(rObj).join(', '));
}
return rObj;
}
function processForm(obj){
var fObj=getInputObject(obj);
var name=fObj.filename;
google.script.run
.withSuccessHandler(function(rObj){
document.getElementById("btn").disabled=true;
var html='<br />Go To File:' + rObj.filename + '';
$(html).appendTo("body");
})
.createTemplatedGoogleDoc(name);
}
console.log('My Code');
</script>
The Google Script: (FileName: Code.gs)
function onOpen(){
SpreadsheetApp.getUi().createMenu('My Menu')
.addItem("Open Templated Google Doc", 'showMyDialog')
.addToUi()
}
function createTemplatedGoogleDoc(name){
Logger.log(name);
var doc=DocumentApp.create(name);//Creates a google doc
var fldrs=DriveApp.getFileById(SpreadsheetApp.getActive().getId()).getParents();
while(fldrs.hasNext()){
var fldr=fldrs.next();
if(fldr.getName()=="Create Templated Google Doc App"){
var folder=fldr;
}
}
Drive.Files.update({"parents": [{"id": folder.getId()}]}, doc.getId());//puts doc file into same directory as the spreadsheet that contains the script
doc.addHeader().appendParagraph(Utilities.formatDate(new Date(), Session.getScriptTimeZone(), "E MMM dd, yyyy"));
doc.addFooter().appendParagraph(Utilities.formatDate(new Date(), Session.getScriptTimeZone(), "E MMM dd, yyyy"));
//doc.getBody().getChild(0).removeFromParent();
doc.saveAndClose()
var rObj={url:doc.getUrl(),filename:doc.getName()}
return rObj;
}
function showMyDialog(){
var ui=HtmlService.createTemplateFromFile('docwithdate').evaluate();
SpreadsheetApp.getUi().showModelessDialog(ui, 'My Doc with Date');
}
function doGet(){//if you want a web app this is helpful
return HtmlService.createTemplateFromFile('docwithdate').evaluate();
}
function include(filename){//this is the include that the template uses
return HtmlService.createHtmlOutputFromFile(filename).getContent();
}
It's a pretty simple script. I hope it helps you get a start.
In accordance with the proposal of #TheMaster it is necessary to do this:
code.gs
function Test(formObject){
var a = new Error( JSON.stringify({msg:"Allready present "+ formObject,code:99}));
throw a;
}
TestForm.html
// removing "Error: " from message string to get our json back
var json = error.message.replace("Error: ",'')
var msg = JSON.parse(json).msg;
var code = JSON.parse(json).code;
That is, we put json into the attribute message of the Error object, and then, by cutting our json, we parse it and get the necessary values.
This is not exactly the answer to the question, but a good way to solve the problem.

Javascript cannot encode the £ sign

I have <meta charset="utf-8" /> on my website, my files are in UTF-8 encoding and I have put charset="utf-8" on the script tag - and it still doesn't work.
Below is my code
<input type="text" id="danewcontent1" name="danewcontent1"
value="£890">
<script charset="utf-8">
function escapePercent(str) {
return str.replace(/%/g, '%25');
}
$(function() {
var post_id = 1;
var daplaincontent = $("#danewcontent1").val();
alert(daplaincontent);
var danewcontent = escapePercent(escape(daplaincontent));
prompt("Copy the value below into http://urldecode.org and keep clicking decrypt", danewcontent);
// decode the URLEncode here, and keep clicking "decode"
// https://urldecode.org
});
</script>
It encodes £ as %25A3890 which is %A3890 decoded which is �890 decoded.
I have a JS Fiddle illustrating this problem here.
https://jsfiddle.net/desbest/dyz9zta6/
I think you need to stop trying to re-invent the wheel and use built-in browser encoding and decoding. Your simply handling the escape the way you do is not working for you.
$(function() {
var post_id = 1;
var daplaincontent = $("#danewcontent1").val();
alert(daplaincontent);
var encoded = encodeURIComponent(daplaincontent);
alert(encoded);
var decoded = decodeURIComponent(encoded);
alert(decoded); // this gives back the £890
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="danewcontent1" name="danewcontent1"
value="£890">

Javascript HTML forms : unicode user input to unicode output

I'm trying to make a simple multi-search tool for learning German. When I put in certain characters, they change. For example, ü is %FC, ä is %E4, ö is $F6, ß is %DF. I assume somewhere the characters are being converted to some other character set other than Unicode
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<script language="javascript" charset="UTF-8">
function basicSearch()
{
//document.basicForm.basicWord.value = '\u1495';
var basicSubmit=document.basicForm;
var basicWord = escape(basicSubmit.basicWord.value);
document.getElementById("demo").innerHTML = basicWord;
window.open("https://translate.google.com/#de/en/" + basicWord);
return false;
}
</script>
</head>
<body>
<form name="basicForm" onSubmit="return basicSearch();" accept-charset="UTF-8">
<input type="text" name="basicWord">
<input type="submit" name="SearchSubmit" value="Search">
</form><br>
<p id="demo"></p>
</body>
</html>
Its a good idea to consider http encoding any URIs you are manually constructing. In this case we can use encodeURIComponent on the text of the input to properly http encode data passed in the URI.
// früh -> early
var basicWord = encodeURIComponent(basicSubmit.basicWord.value);
// basicWord = 'fr%C3%BCh';
Other cases might warrant using encodeURI. See this question for more info.
var basicWord = escape(basicSubmit.basicWord.value);
JavaScript's escape()/unescape() encoding is a bizarre custom format you almost never want to use. For encoding URL parameters using the actual real URL rules, the function you want instead is encodeURIComponent().
document.getElementById("demo").innerHTML = basicWord;
Avoid writing HTML markup to the document, you get HTML-injection problems which can lead to cross-site scripting security holes. Write to textContent instead to write normal text.
window.open("https://translate.google.com/#de/en/" + basicWord);
(Incidentally Google Translate also accepts form parameters: q for text to translate, sl for source and tl for target language. So FWIW you could do this with a simple form without JS.)
Thank you both. If anyone is interested, below is the final coding. I made it to help create flash cards for ANKI using Gabriel Wyner's youtube vids and his multi-tool.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Page Title</title>
</head>
<body>
<script>
function basicSearch() {
var basicSubmit=document.basicForm;
var basicWord = encodeURIComponent(basicSubmit.searchterms.value);
window.open("https://de.wiktionary.org/w/index.php?search=" + basicWord + "&title=Spezial:Suche&go=Seite&searchToken=480i5tddc2tqpr6njyi8gx2oa");
window.open("http://forvo.com/search/" + basicWord + "/");
window.open("https://www.google.de/search?q=" + basicWord + "&biw=1280&bih=611&source=lnms&tbm=isch&sa=X&ved=0ahUKEwiOydnfssfRAhVCqlQKHaPSDvoQ_AUIBigB#q=" + basicWord + "&tbm=isch&tbs=isz:m");
window.open("https://translate.google.com/#de/en/" + basicWord);
return false;
}
function actionSearch() {
var actionSubmit=document.actionForm;
var actionWord = encodeURIComponent(actionSubmit.searchterms.value);
window.open("https://www.google.de/search?q=" + actionWord + "&biw=1280&bih=611&source=lnms&tbm=isch&sa=X&ved=0ahUKEwiiwtDttMfRAhVkx1QKHc6PCgMQ_AUIBigB#tbs=isz:m%2Citp:animated&tbm=isch&q=" + actionWord);
return false;
}
</script>
<form name="basicForm" onSubmit="return basicSearch();">
Search for a basic word:
<input type="text" name="searchterms">
<input type="submit" name="SearchSubmit" value="Search">
</form><br>
<form name="actionForm" onSubmit="return actionSearch();">
Search google for animation:
<input type="text" name="searchterms">
<input type="submit" name="SearchSubmit" value="Search">
</form><br>
German quotes/sayings
<h2>English links for gifs: (for verbs or other)</h2>
http://giphy.com/<br>
http://www.reactiongifs.com/<br>
https://www.reddit.com/r/gifs/<br>
https://www.reddit.com/r/reactiongifs/<br>
https://www.reddit.com/r/analogygifs<br>
https://www.reddit.com/r/HighQualityGifs/<br>
https://www.reddit.com/r/DANCEGIFS/<br>
http://www.gifbin.com/<br>
</body>
</html>

I want to get two integers from a user via a text input, find the difference between the two numbers and divide that number by 25. How do I do this?

I'm making a small website as a test. Very new to JavaScript and HTML forms so I thought i'd throw myself into what I consider to be the deep end and give it a go.
I'm trying to get an interger to be displayed on the page, that is the result of a few calculations.
I want to find the difference between the first number (current value), and the second number (desired value) and then divide that number by 25 and store that as a variable. I then want to display that variable inside a message.
My current HTML :
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="css/stylesheet.css">
<title>MMR calculator</title>
</head>
<body>
<h1>Type in your current MMR, and your desired MMR and click "Calculate"</h1>
<form>
<input type="text" id="currentRating" placeholder="What is your current MMR?">
<input type="text" id="desiredRating" placeholder="What is your desired MMR?">
<input type="submit" onclick="calculate()">
</form>
<script src="js/main.js"></script>
</body>
</html>
My current JavaScript :
function calculate() {
var currentRating = document.getElementById("currentRating");
var desiredRating = document.getElementById("desiredRating");
var difference = desiredRating - currentRating;
var gamesToPlay = difference / 25;
document.write("You need to play " + gamesToPlay + " to get to " + desiredRating);
}
You are 99% there. All you have to do is change
var currentRating = document.getElementById("currentRating");
var desiredRating = document.getElementById("desiredRating");
into
var currentRating = parseInt(document.getElementById("currentRating").value);
var desiredRating = parseInt(document.getElementById("desiredRating").value);
The way you had it, those variables just held the HTML (technically, DOM) elements themselves, and not the values that were in them. This gets the values and then turns them into integers so you can do math with them. If you do this, your site do exactly what you want it to do.
Be careful:
var currentRating = document.getElementById("currentRating").value;
is a String (text) value... to be sure of int value you can do
try{
var currentRatingInt = parseInt(currentRating);
}catch(e){
alert(currentRating + " is not an integer");
}
If you like to display result in page you can use a DIV with and id and do:
document.getElementById("idOfYourDiv").innerHTML = "What you like to display in div";
hope this code will help :
html :
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="css/stylesheet.css">
<title>MMR calculator</title>
</head>
<body>
<h1>Type in your current MMR, and your desired MMR and click "Calculate"</h1>
<div>
<input type="text" id="currentRating" placeholder="What is your current MMR?">
<input type="text" id="desiredRating" placeholder="What is your desired MMR?">
<button onclick="calculate();">Calculate</button>
</div>
<script src="js/main.js"></script>
</body>
</html>
javascript :
function calculate() {
var currentRating = document.getElementById("currentRating").value;
var desiredRating = document.getElementById("desiredRating").value;
var gamesToPlay = (desiredRating - currentRating) / 25;
gamesToPlay = Math.abs( parseInt(gamesToPlay) );
alert("You need to play " + gamesToPlay + " to get to " + desiredRating);
}
Subtract first field from the other, and if the value is not greater than 0 multiply by -1.
Divide that by 25.

Posting form values securely from one page to another on client-side using pure Javascript and NO server-side technology

I need to POST form values from one page to another using Javascript.
Now, I know that I could use a server-side technology like ASP.Net or PHP to post values but I am not allowed to use any server side script.
I am aware that using the GET method, I can pass the form values as a query string but the values will not be passed securely (which is an important requirement!)
The conditions listed below:
This code should take the values that are posted to the page and
repost to target page. HTTP POST only (not get).
In no cases, even error, the request should not stop on this bridge page.
The script needs to handle multiple posted values.
Try to use standard javascript (no 3rd party library)
Script needs to work in IE, FF, Safari, most standard browsers
Can anyone please help me find a solution to this or point me to some resource that will help me find the soln? Thanks in advance. Below is the code for passing values as a query string. Can I modify this so that my above requirements are satisfied?
FORM
<html>
<head>
<title>Test</title>
<script type="text/javascript">
function goto_page(page) {
var usbnum = document.getElementById('usbnum').value;
var usbcode = document.getElementById('usbcode').value;
var q_str = '?usbnum=' + usbnum + '&usbcode=' + usbcode;
var url = page + q_str;
window.location = url;
}
</script>
</head>
<form id="form1" method="post">
<div>
USB No: <input name="usbnum" id="usbnum" type="text" size="80" /><br />
USB Code: <input name="usbcode" id="usbcode" type="text" size="80"/>
</div>
Next
</form>
</body>
</html>
BRIDGE PAGE
<html>
<head>
<title>Bridge Page</title>
<script type="text/javascript">
function get_params() {
var url = window.location.href;
var q_str_part = url.match(/\?(.+)$/)[1];
var val_pairs = q_str_part.split('&');
var params = {};
for (var i = 0; i < val_pairs.length; i++) {
var tmp = val_pairs[i].split('=');
params[tmp[0]] = typeof tmp[1] != 'undefined' ? tmp[1] : '';
}
return params;
}
function write_params() {
var params = get_params();
var txt = 'Hello ';
for (var i in params) {
txt += params[i] + ' ';
}
var body = document.getElementsByTagName('body')[0];
body.innerHTML += txt;
}
function write_params() {
var params = get_params();
var num_container = document.getElementById('usbnum');
var code_container = document.getElementById('usbcode');
num_container.innerHTML = params.usbnum;
code_container.innerHTML = params.usbcode;
}
</script>
</head>
<body onLoad="write_params()">
</body>
</html>
POST data can only be handled by server side code. There is no way you can use them in your javascript without help from a server side code.
You can only use GET or you can think about cookies. But at other hand, why do you want to change current page?! you can use AJAX to load more data without refreshing and no need of posting or getting variables.

Categories