Javascript cannot encode the £ sign - javascript

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">

Related

have to encode by HTML link with base64

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 ?

Issue Storing File Paths in Javascript Array from C#

I am trying to store all of file paths from a string array in C# into a Javascript array and it works and stores them all in the array but the path's slashes are removed so the file path doesn't read as normal and produces an error. The file path is shown in the following and as you can see in the end of the path everything collides together because the slashes disappear.:
If the slashes were in there then the file path should be able to be read in my code sample I will include which I have tested with file paths. I was just wondering how to, in my code, have the slashes retained in javascript.
What my code does is pass in an array of strings seperated by a semicolon from c# razor code in MVC and then puts each one in an array in Javascript and this is where it strips the slashes. Then the image is displayed using URL.Content and the file path.
ANY HELP IS APPRECIATED!
Code
<!DOCTYPE html>
<html>
<head>
#model Tuple
<string, string[]>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-
scale=1.0">
<title>My ASP.NET Application</title>
<script src="//code.jquery.com/jquery-2.1.1.min.js" type="text/javascript"></script>
</head>
<body>
<div style="width:800px;height:400px;border:3px solid #000;margin:0
auto;margin-top:70px;position:relative;">
<img src="" style="width:100%;height:100%;" id="img" />
<p style="position:absolute;top:45%;font-
size:22px;color:#fff;left:10px;cursor:pointer;" id="left">
< </p>
<p style="position:absolute;top:45%;font-
size:22px;color:#fff;right:10px;cursor:pointer;" id="right">></p>
</div>
</body>
</html>
<script type="text/javascript">
var arr = [];
var first = "#Model.Item1";
counter = 0;
#foreach(string i in Model.Item2) {
<
text > arr.push("#i") < /text>
}
$('#right').click(function() {
if (counter == 0) {
} else {
counter--;
}
});
$('#left').click(function() {
if (counter == 0) {
} else {
counter--;
}
});
var image = document.getElementById("img");
image.src = "#Url.Content("~/Practice/Images / ")" + arr[0];
</script>
There is problem with the way you populate the arr object. Somehow javascript escape sequence removes the slashes. Remove this #foreach(string i in Model.Item2) loop and You can directly assign value to arr as below.
var arr = #Html.Raw(Json.Encode(Model.Item2));

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>

Scrape html with js

I'm trying to get the html of www.soccerway.com. In particular this:
that have the label-wrapper class I also tried with: select.nav-select but I can't get any content. What I did is:
1) Created a php filed called grabber.php, this file have this code:
<?php echo file_get_contents($_GET['url']); ?>
2) Created a index.html file with this content:
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<meta charset=utf-8 />
<title>test</title>
</head>
<body>
<div id="response"></div>
</body>
<script>
$(function(){
var contentURI= 'http://soccerway.com';
$('#response').load('grabber.php?url='+ encodeURIComponent(contentURI) + ' #label-wrapper');
});
var LI = document.querySelectorAll(".list li");
var result = {};
for(var i=0; i<LI.length; i++){
var el = LI[i];
var elData = el.dataset.value;
if(elData) result[el.innerHTML] = elData; // Only if element has data-value attr
}
console.log( result );
</script>
</html>
in the div there is no content grabbed, I tested my js code for get all the link and working but I've inserted the html page manually.
I see a couple issues here.
var contentURI= 'http:/soccerway.com #label-wrapper';
You're missing the second slash in http://, and you're passing a URL with a space and an ID to file_get_contents. You'll want this instead:
var contentURI = 'http://soccerway.com/';
and then you'll need to parse out the item you're interested in from the resulting HTML.
The #label-wrapper needs to be in the jQuery load() call, not the file_get_contents, and the contentURI variable needs to be properly escaped with encodeURIComponent:
$('#response').load('grabber.php?url='+ encodeURIComponent(contentURI) + ' #label-wrapper');
Your code also contains a massive vulnerability that's potentially very dangerous, as it allows anyone to access grabber.php with a url value that's a file location on your server. This could compromise your database password or other sensitive data on the server.

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