Script to pick up the HTML value of a page? Explanation inside - javascript

I am quite the noob at anything other than some HTML, CSS etc, basic website stuff. My javascript is pretty non-existant too. However we were quoted £2,500 by the people who develop our website to add Paypal on the checkout page! They use a fancy 3rd party program which is a standalone software made by themselves that contains all the products etc. We pay monthly to have access to that and make all website changes (such as price, product name etc) in that.
To cut a long story short, I had a look around and found this:
<script src="paypal-button.min.js?merchant=YOUR_MERCHANT_ID"
data-button="buynow"
data-name="My product"
data-amount="1.00"
async
></script>
Now, can I change the data-amount field to pick up what the "value" is on the page in the HTML? That way I can simply just add a button that picks that up. Which would work with paypal.
<div class='basketLabel'>Total Amount To Pay:</div>
<span>£</span>1,038.00</li>
<input type=hidden name='amount' value='1,038.00'>
Basically, how can I get the javascript code to pick up the value from the HTML (or somewhere else). I only have access to the full HTML of the page.

I am not sure how many of these data fields you have on a page but you could write a JS method to dynamically assign the values of the given HTML.
I would start by giving the HTML you're working with some ID's.
<script id="paypalScript" src="paypal-button.min.js?merchant=YOUR_MERCHANT_ID"
data-button="buynow"
data-name="My product"
data-amount="1.00"
async
onload="assignAmount"
></script>
<div class='basketLabel'>Total Amount To Pay:</div>
<span>£</span>1,038.00</li>
<input id="amount" type=hidden name='amount' value='1,038.00'>
Then write a method to execute onload.
function assignAmount(){
var amtElm = document.getElementById('amount');
var scriptElm = document.getElementById('paypalScript');
scriptElm.dataset.amount = amtElm.value;
}
Then attach the method to the onload event of the script element. Putting the script tag below your data field in the HTML should prevent any load issues you might run into.

Related

Creating HTML with intentional HTML Injection

I am a cybersecurity student trying to understand some basic HTML injections. I have been working on this code for a few days and can't understand what I am doing wrong. The code that I have currently does allow for injection, for example if I put <h1>test</h1> into the textbox, it will display test as a header. But if I try <script>alert(1)</script> it won't actually run the script. I have tried setting the value of the text box to "" or with the thought that I could close out that line by inputting the following into the textbox: "><script>alert(1)</script>
I've also tried to cancel out the remainder of the code by adding a comment to the end like this: <script>alert(1)</script><!--
I've tried a number of combinations of each with no luck. Now I actually need to be able to inject a script since I'm playing around with CSP and how that affects injection of scripts into the webpage. I currently DO NOT have a csp specified that would restrict the JavaScript from running. Some other things I've tried include using different browsers, changing browser security, and ensuring that JavaScript is enabled in the browser. Any help would be greatly appreciated!!
<html>
<script language='JavaScript'>
function getwords(){
textbox = document.getElementById('words');
label = document.getElementById('label');
label.innerHTML = textbox.value;
}
</script>
<body>
<input type="text" id="words">
<input type="button" onclick="getwords()" id="Button" value="Enter" />
<label id="label">
</label>
</body>
</html>
That's because <script>s run at page load, and, when the label's content change, the scripts have ran already.
However, if you inject <script> tags to a different page (through the backend (XSS means Cross-Site Scripting)), it does work.
Alternatively, to make it work in a scenario, where the content injected after page load (like your case), you can use JS events (like onclick) to run your code:
<div onclick="alert(1)">Click me!</div>
Or, to execute it without user interaction, you could use an <iframe>'s onload event:
<iframe onload="alert(1)" style="display:none"></iframe>
to execute javascript from your form, you can try:
<iframe src=javascript:alert(1)>
or
<img src=x onerror=alert(1)>
Also worth noting:
script elements inserted using innerHTML do not execute when they
are inserted.
To manually execute JavaScript, you may do the following
without editing your HTML file, add this to the Input field on your Browser.
<iframe onload="alert(1)" style="display:none"></iframe>
More information on why this works here
More on how you can perform actions like this here: developer.mozilla.org
<html>
<script language='JavaScript'>
function getwords(){
textbox = document.getElementById('words');
label = document.getElementById('label');
label.innerHTML = textbox.value;
}
</script>
<body>
<input type="text" id="words">
<input type="button" onclick="getwords()" id="Button" value="Enter" />
<label id="label">
</label>
</body>
</html>

parse <script> tag with js/jQuery

I have a HTML page where a user is able to edit a HTML resource (using ACE Editor). Within this HTML source, there is a <script>-tag, which does some pretty basic stuff.
Is there any elegant solution to parse the script tag in order to (e.g.) evaluate the variables used within the script tag? For "normal" tags I use parseHTML() to have the html as a jQuery object.
From this example, I would like to retrieve the value of $myVal (which is "f00") and write it to #myLabel:
<textarea id="myScript" rows="5" readonly>
<script>
$myVal = "f00";
</script>
</textarea>
<label id="myLabel">Hello</label>
$(function(){
$scriptVar = $('#myScript').text;
// parse the $scriptVar
// retrieve the value of, $myVal, write it to #myLabel
//$myParsedValue = ???
//$('#myLabel').text('bar!');
});
And here is the fiddle: https://jsfiddle.net/stepdown/jqcut0sn/
Is this possible at all? I don't really care about vanilla js, jQuery, regex or maybe even an external library for that purpose.
Thanks to #JeremyThille, who pointed me to the right direction. I found out, what I want to achieve is possible through jQuerys $.globalEval() - see the official documentation.
Basically what globalEval() does: it runs the script which is written in the <textarea> and makes the variables / functions globally accessible.
IMPORTANT: this implies, that syntax errors (etc) by the user will break the evaluation, and sequential functionality could be flawed. Also, the new variables are GLOBAL, so basically a user could rewrite scripts on the hosting page. (In my case both problems are of minor importance, since this is an internal application for trained users - they also have syntax highlighting through the amazing ACE editor. But I wanted to make sure to point it out. Also, there are several articles regarding the risks/ouch-moments when using eval()...)
I updated the fiddle to achieve what I wanted: https://jsfiddle.net/stepdown/Lxz7q6uv/
HTML:
<textarea id="myScript" rows="5" readonly>
$myVal = "f00";
</textarea>
<hr />
<label id="myLabel">Hello</label>
Script:
$(function(){
var myScriptContent = $('#myScript').text();
$.globalEval(myScriptContent);
console.log($myVal);
$('#myLabel').text($myVal);
});

Toggle Visibility of Separate Javascript Files on Same Wordpress Page

Let me preface by saying this is all in relation to a Wordpress page. My knowledge of JS is lacking at best and the concept of installing/loading/enqueueing a function on one area of the site and then calling that function in another area of the site is a something that makes sense to me in my head but is very new to me in practice and might need a little explaining.
I have two separate javascript files that I would like to load on a single page, but toggle visibility/display of either based on radio button input. The JS is provided by a 3rd party and is offsite. Their provided code is this:
<script src="https://toolkit.rescuegroups.org/j/3/FzemP6HU/toolkit.js"></script>
and
<script src="https://toolkit.rescuegroups.org/j/3/4ANRW3x8/toolkit.js"></script>
Each file presents a separate set of filtered results from their database. How can I incorporate both onto a page but only have one or the other showing based on a radio button form input? I would like the page to start off with nothing visible (hopefully giving time for both JS to load in the background while the user selects an option) and then show one or the other depending on what they selected.
You can see a single one of these in action at http://pricelesspetrescue.org/adoptable-dogs/. I'm trying to incorporate the use of an additional file on that same page based on input from the user and only showing one or the other rather than both.
I have tried to manage the following
<script src='http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js'></script>
<script type='text/javascript'>
function displayForm(c) {
if (c.value == "2") {
jQuery('#claremontdogContainer').toggle('show');
jQuery('#chdogContainer').hide();
}
if (c.value == "1") {
jQuery('#chdogContainer').toggle('show');
jQuery('#claremontdogContainer').hide();
}
};
</script>
<label>Please select a location to view:</label>
<form>
<input value="1" type="radio" name="formselector" onClick="displayForm(this)"></input>Chino Hills
<input value="2" type="radio" name="formselector" onClick="displayForm(this)"></input>Claremont
</form>
<div style="display:none" id="chdogContainer">
<script src="https://toolkit.rescuegroups.org/j/3/FzemP6HU/toolkit.js"></script>
<script type="text/javascript">
</script>
</div>
<!-- If I uncomment this second block the whole thing breaks
<div style="display:none" id="claremontdogContainer">
<script src="https://toolkit.rescuegroups.org/j/3/4ANRW3x8/toolkit.js"></script>
<script type="text/javascript">
</script>
</div>
-->
This gets pretty close to what I need. The problem I have is the second script load seems to conflict with the functions they provide in the script. It will display the initial result but does not carry any of the functionality that it should have. http://pricelesspetrescue.org/test-page/ Nothing is clickable inside those results and should be.
Been searching through various similar posts and the wordpress codex and...and...I just haven't been able to come up with anything that seems close enough to what I'm looking for to make the answer click in my head.
Edit: It seems that if I only load one of the scripts in either what I have above or the suggested answer below, all functionality is present when loaded. It's the loading of the second toolkit script that is breaking the page. I'm guessing one would need to be loaded then unloaded before loading the second for it to work. Any ideas?
The toolkit.js file you linked adds some common scripts to the DOM (via document.write function, which is not a good solution - see here: http://www.jameswiseman.com/blog/2011/03/31/jslint-messages-document-write-can-be-a-form-of-eval/), then populates an array (toolkitObjects) with a series of variables that are custom per file and finally loads some other scripts.
It also seems that each file loads a div with a specific class containing all the pets, and each div is identifiable by a specific class ( "rgtk-SOMEID" ) and therefore can be shown/hidden via javascript.
Here is an example of what you can obtain using the div class:
http://jsbin.com/loneyijuye/edit?html,output

auto update the html dom for all the users whenever there's change

I am sorry for asking such a noob question. But I saw a video very long time ago and I think it was a framework based on jquery, where if a user makes some CRUD changes to an object, the object's properties are auto updated not only for 1 user, but on all the other users browser. I am trying to find it but I am all lost! I would really really appreciate if you could help me out. Thank you!
Lets say you have a html form that looks like this
<form>
<input type="text" name="firstName" value="Jackson" />
<input type="text" name="lastName" value="Rivera" />
<textarea name="lifestory">
When i was 2yo, spot died...
</textarea>
</form>
simply add an OnChange event on every element you want to dynamicly change:
<form>
<input .. .. onchange="shareValueWithOthers(this.name, this.value)"/>
<input .. .. onchange="shareValueWithOthers(this.name, this.value)"/>
<textarea onchange="shareValueWithOthers(this.name, this.innerHTML)">
When i was 2yo, spot died...
</textarea>
</form>
Notice that a change of the elements value (or in the case of the textarea - it's contents) causes the function shareValueWithOthers(this.name, this.value) starts to run. this.name is the variable for the name, this.value is the variable for the value, this.innerHTML is the variable for the contents.
Now you have to write a Javascript function so you can send the changes to the server. Look into AJAX. Make a function that sends a POST request to your PHP script.
Your PHP script should save all the values either in a database, or in JSON-format in a file on the server. JSON is the easiest. Look into JSON PHP PARSER.
Last but not least. If you do the right thing, and make sure that every new value that a user enters gets updated in your json file by your PHP script. You can make the last step. which is to make a javascript function that retrieves the JSON file. JSON stand for JavaScript Object Notation, so your javascript can use this right away.
What you will do next, is to change all the values in your DOM that look different from the values in your retrieved JSON object.
two type of protocol, Websocket or WebRTC.
socket.io is Websocket very popular and easy.
gevent-socketio for python
Plenty base on node.js. sailsjs, deployd, meteor

Razor syntax in JavaScript code block

I want to know if it is a good practice to use razor in JavaScript code. For example:
<script type="text/javascript">
var variable = #some.Id
</script>
Or it's better to create hidden value and then take it with JavaScript, like this?
<input type="hidden" id="someId" value"#some.Id" />
<script type="text/javascript">
var variable = $('#someId').val();
</script>
EDIT:
#{
var formVariables = serializer.Serialize(new
{
id = Model.Id,
name = Model.Name,
age = Model.Age
});
<input type="hidden" id="header_variables" value="#formVariables"/>
<script type="text/javascript" src = "/Scipts/..."></script>
}
Is this good solution?
I personally would go with an extension of the 2nd option and create a seperate .js file. The reason being, if you delegate work out to a 3rd party to take care of the jquery/javascript parts of the UI, then they need not have any sight of the backend functionality.
There are a variety of ways to use html5 attributes (i.e. data-attribute='foo') on the inputs which would allow you to 'decorate' your inputs with a cargo of properties which could be parsed inside the external .js file.
A very brief example:
in your view:
<input type='text' id='myId' data-action='#Url.Action("MyAction")' class='myClass' />
in your .js file:
var targetAction = $('#myId').attr('data-action');
this gives complete separation between the .js and the views. It does require a degree of planning of course.
Hope this helps
Razor will be parsed at server-side and replaced by relevant output. Therefore, in my opinion it is totally indifferent, if you place it in Javascript or HTML - at client side only the output value will be visible. Thus, in the above example I would choose the first option (place it directly in JS), since you will not have the otherwise unnecessary hidden input field.
I don't think there is a correct answer to this question; only pros and cons.
Pros of using Razor in Javascript
Script is bound to your view model; so model changes will get picked up automatically, and errors will get caught at compile time.
Cons
Script is mixed with markup, contrary to web design best practices (put script at the bottom so that it will never break your page).
Script cannot be compiled/minified, because, again, it's mixed in with your markup.

Categories