Access to the specific content of an inside code of a script - javascript

Please, can anybody tell me how can I access to the value of "41" in this inner script of a website? I just tried this, but it doesnt work
I tried with:
var elem = document.getElementById("back-in-stock-helper");
I only need the number 41, and the example code I need to access is this
<script id="back-in-stock-helper">
var _BISConfig = _BISConfig || {};
_BISConfig.product.variants[0]['inventory_quantity'] = 41;
</script>
Thanks!
Solved:
var elem = document.getElementById("back-in-stock-helper");
var elem2 = elem.textContent;
var ult_pos = elem2.lastIndexOf('=');
var stock = elem2.substring(ult_pos);

Related

Attach script tag code to dom element for execution , alternate for document.write

var str = '<script>alert(1)</script>';
var decoded = $("<div/>").html(str).text();
//document.write(decoded); THIS WORKS, but I want to avoid using document.write
var para = document.createElement("script");
var node = document.createTextNode(decoded);
para.appendChild(node);
var element = document.getElementById("div1");
element.appendChild(para);
jsfiddle.net/1bz9mL7k/2
The problem is that due to presence of script tag, this createElement method won't work. Closing script tag in the encoded str will cause syntax error (Uncaught SyntaxError: Unexpected token '<').
Document.write works all perfect but I want to avoid due to its disadvantages of parser-block etc.
In real use case, the encoded string will be of some ads which will be entered by users. Please note we can't remove script tags from code they enter and are saving it in database by using htmlentities($adcode).
User input is trusted, so no issue of any xss vulnerability which might happen by solution proposed.
One of the sample user input :
<script async="async" src="someURL.js"></script>
<script>
var googletag = googletag || {};
googletag.cmd = googletag.cmd || [];
</script>
<div id="xyzid">
<script type="text/javascript">
googletag.cmd.push(function() {
googletag.pubads().display("Mobile_ATF_300x250", [300,250],"div-gpt-ad-0");
});
</script>
</div>
There can be various different version of ad set with unknown pattern.
Additional not so relevant info : We will be further using something like <script> if(var==1) { codeblock1 } else { codeblock2} </script> (here codeblock is 1st code blockset). So any soln which includes use decoded user input directly won't be useful as the script block will break in if-else.
So for answering this question I had to change first the ad2 since it had inside the script tag, wich is no longer necessary,what you can do is to create an element called Script, of type text/javascript and insert the text, then insert it into the body.
var ad2 = `alert(12)`;
var decoded = decodeHtml(ad2);
decoded = decoded.replace(/(<([^>]+)>)/ig,'')
var para = document.createElement("script");
para.type = "text/javascript";
para.text = decoded
var element = document.getElementById("div12")
element.appendChild(para)
Here's a working demo in jsfiddle on how to do It.
https://jsfiddle.net/59g24do1/
EDIT
For multiples scripts use this instead; what we do here is first we create an array of the tags,after that we create one by one with the previous function, doing a for loop in order to execute them all. = >
function getParagraphs(htmlString) {
const div = document.createElement("div");
div.insertAdjacentHTML("beforeend", htmlString);
return Array.from(div.querySelectorAll("script"))
.map(script => script.outerHTML);
}
for(let i = 0;i<decoded.length;i++){
if(decoded[i].includes("src")){
let srcString = decoded[i].match('src="(.*)"')
var para = document.createElement("script");
let aux = decoded[i].replace(/(<([^>]+)>)/ig,'')
para.type = "text/javascript";
para.src = srcString[1]
para.text = aux
var element = document.getElementById("div12")
element.appendChild(para)
}else{
let aux = decoded[i].replace(/(<([^>]+)>)/ig,'')
let para = document.createElement("script");
para.type = "text/javascript";
para.text = aux
let element = document.getElementById("div12")
element.appendChild(para)
}
}
For complete example use there's a jsfiddle
https://jsfiddle.net/f2Leu74g/2/
I was able to resolve it by below code, thought to update if someone in future is stuck on the same problem.
var ad = "whatever encoded here script code";
function decodeHtml(html) {
return $("<textarea/>").html(html).text();
}
function fetch(id, html) {
var elm = document.getElementById(id);
elm.innerHTML = html;
var scripts = elm.getElementsByTagName("script");
var scriptsClone = [];
for (var i = 0; i < scripts.length; i++) {
scriptsClone.push(scripts[i]);
}
for (var i = 0; i < scriptsClone.length; i++) {
var currentScript = scriptsClone[i];
var s = document.createElement("script");
// Copy all the attributes from the original script
for (var j = 0; j < currentScript.attributes.length; j++) {
var a = currentScript.attributes[j];
s.setAttribute(a.name, a.value);
}
s.appendChild(document.createTextNode(currentScript.innerHTML));
currentScript.parentNode.replaceChild(s, currentScript);
}
}
var decoded = decodeHtml(ad);
fetch('YourDivID',decoded);

How to update URL address using ASP when based on JSON object

I'm making an application of a list of races in a table, this information is gotten from a JSON api. Upon selecting a race in a table I need a window to pop up with the name of the race in the url address bar, so something like asp?=race_name at the end.
How would I go about completing this?
I've looked this up but can't seem to find an answer, my guess is I'm googling the wrong thing as I'm not good at explaining
for (let i = 0; i < jsonObj.length; i++) {
document.getElementById(jsonObj[i].id).onclick = function () {
var newWin = window.open("","","width=700,height=700");
newWin.onload = function () {
var doc = newWin.document; // Create new document in window
var raceName = document.createElement('h3');
var distance = document.createElement('p');
var location = document.createElement('p');
var curPos = document.createElement('p');
var difference = document.createElement('p');
raceName.textContent = jsonObj[i].race_name;
distance.textContent = jsonObj[i].distance;
location.textContent = jsonObj[i].venue_name;
doc.body.appendChild(raceName);
doc.body.appendChild(distance);
doc.body.appendChild(location);
}
}
Here the window pops up and includes the correct information, I now just need to include code that would update the url address to include race name.

How to read a firebase Data using HTML5 and Javascript?

When I want to read the data of my Firebase, nothing appears.
I have tried to read the data using a script for this.
This is my HTML code:
<html>
<head>
<title>Javascript Firebase</title>
Humidity: <humidity></humidity><br>
Clock: <clock></clock><br>
</head>
<body>
and this is my script:
<script type="text/javascript">
var database = firebase.database('javascript-firebase-6567d');
var h document.querySelector('humidity');
var c = document.querySelector('clock');
var pad = function(x){
return x < 10 ? '0' +x : x;
}
var ShowClock = function() {
var d = new Date();
var h = pad(d.getHours());
var m = pad (d.getMinutes());
var s = pad (d.getSeconds());
c.innerHTML = [h,m,s].join(':');
}
setInterval(ShowClock,1000);
var myRef = Firebase('https://javascript-firebase-6567d.firebaseio.com/rooms');
myRef.on('child_changed',function(snapshot){
data = snapshot.val();
h.innerHTML = data.humidity;
});
</script>
The results that I hope is to see the changes that the child "humidity" shows but currently I can not see the results of the clock or the humidity
This code:
myRef.on('child_changed',function(snapshot){
data = snapshot.val();
h.innerHTML = data.humidity;
});
The child_changed event only fires when the data in the location changes. If you're trying to show the current child nodes under a location, you'll want to use child_added:
myRef.on('child_added',function(snapshot){
data = snapshot.val();
console.log(data);
});
The child_added fires immediately after attaching the listener for any existing child node, and then subsequently for any new nodes that are added.

How to update HTML table When updating Firebase?

I'm using child_added and child_changed. The child added works perfectly fine, but the child_changed makes a duplicate in my table. Please help me overcome this. Here is my code:
var rootRef = firebase.database().ref().child("REPORTS").child(date);
rootRef.on("child_added", function(snapshot){
var date = snapshot.child("dateAndTime").val();
var lat = snapshot.child("latitude").val();
var long = snapshot.child("longitude").val();
var link = snapshot.child("link").val();
var report = snapshot.child("report").val();
var status = snapshot.child("status").val();
var needs = snapshot.child("needs").val();
$("#table_body").append("<tr><td>" +date+"</td><td>"+report+"</td><td>"+lat+"</td><td>"+long+"</td><td>"+status+"</td><td>"+needs+"</tr>");
});
rootRef.on("child_changed", function(snapshot){
var date = snapshot.child("dateAndTime").val();
var lat = snapshot.child("latitude").val();
var long = snapshot.child("longitude").val();
var link = snapshot.child("link").val();
var report = snapshot.child("report").val();
var status = snapshot.child("status").val();
var needs = snapshot.child("needs").val();
$("#table_body").append("<tr><td>" +date+"</td><td>"+report+"</td><td>"+lat+"</td><td>"+long+"</td><td>"+status+"</td><td>"+needs+"</tr>");
});
How can I update my table when a certain value was updated in firebase
Instead of appending a new HTML element, the code that handles child_changed should update the existing HTML element. The easiest way to do this is by ensuring you give the HTML element an id based on snapshot.key in child_added:
var rootRef = firebase.database().ref().child("REPORTS").child(date);
rootRef.on("child_added", function(snapshot){
var date = snapshot.child("dateAndTime").val();
var lat = snapshot.child("latitude").val();
var long = snapshot.child("longitude").val();
var link = snapshot.child("link").val();
var report = snapshot.child("report").val();
var status = snapshot.child("status").val();
var needs = snapshot.child("needs").val();
$("#table_body").append("<tr id='"+snapshot.key+"'><td>" +date+"</td><td>"+report+"</td><td>"+lat+"</td><td>"+long+"</td><td>"+status+"</td><td>"+needs+"</tr>");
});
Then you can look the element up by its id/key in child_changed and update it:
rootRef.on("child_changed", function(snapshot){
var date = snapshot.child("dateAndTime").val();
var lat = snapshot.child("latitude").val();
var long = snapshot.child("longitude").val();
var link = snapshot.child("link").val();
var report = snapshot.child("report").val();
var status = snapshot.child("status").val();
var needs = snapshot.child("needs").val();
$("#"+snapshot.key).replaceWith("<tr id='"+snapshot.key+"'><td>" +date+"</td><td>"+report+"</td><td>"+lat+"</td><td>"+long+"</td><td>"+status+"</td><td>"+needs+"</tr>");
});

How to pass parameters to local Prettydiff.com

I've downloaded a copy of PrettyDiff to embed in my own local application, so I can compare two AJAX loaded files that are in two variables.
Unfortunately, I can't seem to make prettydiff work. Here's how I try :
var example1 = getFile('exemple1.txt');
var example2 = getFile('exemple2.txt');
var output = prettydiff("/*prettydiff.com api.lang: 8, api.mode: diff, api.diffview: inline, api.source:example1, api.diff: example2 */");
document.getElementById("output").innerHTML = output[0];
All I get is "Error: Source sample is missing.".
I've also tried to make an "api" variable that I fill with the parameters, but that doesn't work either.
The documentation doesn't give any example on how to pass the parameters (options, source and diff texts).
Anyone knows ?
Ok, I found out a way to get it working. I still don't know the fuss about the parameters as comments as specified in the docs, but you can create a js object and pass all your parameters :
var api = new Object();
api.mode = "diff";
api.diffview = "inline";
api.lang = 8;
api.source = example1;
api.diff = example2;
var output = prettydiff(api);
You can use prettydiff option like this.
const prettydiff = require("prettydiff");
let options = prettydiff.options;
options.source = content_Old;
options.diff = content_New;
options.diff_format = "html";
options.lang = "script";
options.color = "white";
options.diff_space_ignore = false;
options.diff_view = "sidebyside";
options.lexer = "script";
options.sourcelabel = "Original File";
options.difflabel = "Updated File";
options.mode = "diff";
options.parse_format = "htmltable";
options.list_options = true;
options.crlf = false;
options.force_indent = true;
outputHtml = prettydiff();

Categories

Resources