Extract a variable value in JavaScript code from HTML - javascript

I'm getting the HTML code of a webpage using this parsing library called Kanna. Basically the stripped down version looks like this.
<!DOCTYPE html>
<html lang="en" class="no-js not-logged-in client-root">
<head>
<meta charset="utf-8">
</head>
<body>
<script type="text/javascript">
window._sharedData = {
// Some JSON
};
</script>
<script type="text/javascript">
// Javascript code
</script>
<script type="text/javascript">
// More Javascript code
</script>
</body>
</html>
There are multiple script tags within the body. I want to access the one with the variable named window._sharedData and extract it's value which is a JSON dictionary.
I tried with using regular expressions but it's returning nil. Maybe something's wrong with my pattern?
if let doc = try? HTML(url: mixURL, encoding: .utf8), let body = doc.body, let htmlText = body.text {
let range = NSRange(location: 0, length: htmlText.utf8.count)
let regex = try! NSRegularExpression(pattern: "/<script type=\"text/javascript\">window._sharedData = (.*)</script>/")
let s = regex.firstMatch(in: htmlText, options: [], range: range)
print(s)
}
Or is there a better way to do this?

Here it is:
import Foundation
import Kanna
let htmlString = "<!DOCTYPE html><html lang=\"en\" class=\"no-js not-logged-in client-root\"><head> <meta charset=\"utf-8\"></head><body> <script type=\"text/javascript\"> window._sharedData = { \"string\": \"Hello World\" }; </script> <script type=\"text/javascript\"> </script> <script type=\"text/javascript\"> </script></body></html>"
guard let doc = try? HTML(html: htmlString, encoding: .utf8) else { print("Build DOM error"); exit(0) }
let body = doc.xpath("//script")
.compactMap { $0.text }
.filter { $0.contains("window._sharedData") }
.map { $0.replacingOccurrences(of: " window._sharedData = ", with: "") }
.map { $0.dropLast(2) }
.first
print("body: ", body)
// body: Optional("{ \"string\": \"Hello World\" }")
After that you can check that body not nil and ready

Related

How transform a value into a html element in p5.js?

I’m trying to make a single web page with p5.js, but at some moment I create an input and the value of the input I want to transform into a html tag (more specifically ‘h3’). I already tried the “.html()” as this example: [examples | p5.js], but for some reason this doesn’t work in my context. I’ll let my code below:
let inputName, bttName, yourName;
function setup() {
let inputDiv = createDiv();
inputDiv.id("input-section");
inputDiv.parent("sobre");
inputName = createInput();
inputName.addClass("input-name");
inputName.parent("input-section");
bttName = createButton('enter');
bttName.addClass('btt-name');
bttName.parent("input-section");
bttName.mousePressed(sendName);
}
function sendName() {
let userName = inputName.value();
yourName.html(userName);
}
I need this in as a variable, because after I’ll format it inside a div in css. Is there another way to transform this value?
Thanks
If I'm understanding correctly, you're wanting to output the name that's entered into a h3 element?
In that case you could just use:
yourName = createElement('h3', userName);
like they've done in that reference you linked.
Here's a running example:
let inputName, bttName, yourName;
function setup() {
let inputDiv = createDiv();
inputDiv.id("input-section");
inputName = createInput();
inputName.addClass("input-name");
inputName.parent("input-section");
bttName = createButton('enter');
bttName.addClass('btt-name');
bttName.parent("input-section");
bttName.mousePressed(sendName);
}
function sendName() {
let userName = inputName.value();
yourName = createElement('h3', userName);
}
html, body {
margin: 0;
padding: 0;
}
canvas {
display: block;
}
<!DOCTYPE html>
<html lang="en">
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.4.0/p5.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.4.0/addons/p5.sound.min.js"></script>
<link rel="stylesheet" type="text/css" href="style.css">
<meta charset="utf-8" />
</head>
<body>
<script src="sketch.js"></script>
</body>
</html>

Why can I write to sessionStorage from an iframe on the first try, but not any consecutive tries? (Chrome Version 74)

This issue has shown up in the latest version of Chrome (74.0.3729.108). This is unique to the local filesystem, as I have other ways of loading up neighboring documents in iframes when the app is on a server.
In my app, we have been able to load up documents from the filesystem with JavaScript by writing iframes to the DOM, and then having the document in the iframe write it's innerHTML to sessionStorage. Once the iframe is done loading, we catch that with the onload attribute on the iframe and handle getting the item written to sessionStorage.
I have narrowed this down to some bare-bones code and found that this works only on the first try, and then any tries after the first fail.
Here is a minimal HTML document:
<!DOCTYPE html>
<html>
<head>
<title>Chrome iFrame Tester</title>
<script src="iframe-load.js"></script>
</head>
<body onload="OnLoad()">
<div id="result"></div>
</body>
</html>
Here is the JavaScript:
var urls = ['file://C:/Users/afrench/Documents/Other/Misc%20Code/Chrome%20iFrame/Doc1.html',
'file://C:/Users/afrench/Documents/Other/Misc%20Code/Chrome%20iFrame/Doc2.html'];
HandleLoad = function () {
'use strict';
var data;
try {
data = window.sessionStorage['data'];
delete window.sessionStorage['data'];
} catch (ignore) {
// something went wrong
}
var container = document.getElementById('container');
window.document.body.removeChild(container);
if (data !== null && data !== undefined) {
var resultContainer = document.getElementById('result');
resultContainer.innerHTML += data;
}
if (urls.length > 0) {
OnLoad();
}
}
function OnLoad() {
var url = urls[0];
if (url) {
urls.splice(0, 1);
var container = document.createElement('div');
container.id = 'container';
container.style.visibility = 'hidden';
window.document.body.appendChild(container);
container.innerHTML = '<iframe src="' + url + '" onload="HandleLoad();"></iframe>';
}
}
In the filesystem, we have the HTML written into index.html, and right next to it are two minimal HTML files, Doc1.html and Doc2.html. Their contents are both identical except the identifying sentence in the body's div:
Neighbor document HTML:
<!DOCTYPE html>
<html>
<head>
<title>Chrome iFrame Tester</title>
<script>
function OnLoad() {
try {
window.sessionStorage['data'] = window.document.body.innerHTML;
} catch {
// no luck
}
}
</script>
</head>
<body onload="OnLoad()">
<div>This is Doc 1's content!</div>
</body>
</html>
When this is run, we should see the content HTML of the two neighbor documents written to the result div in index.html.
When I run this minimal example, I can see that the content is successfully written to sessionStorage and then to the DOM for the first document, but the next try fails. What can I do to get it to work consistently, and what is happening here that it fails?
I'm not sure what is causing the weird behavior, so hopefully someone else can provide some insight on what exactly is going on here.
In the meantime, here is an alternative solution using window.postMessage:
index.html
<!DOCTYPE html>
<html>
<head>
<title>Chrome iFrame Tester</title>
<script src="iframe-load.js"></script>
</head>
<body onload="OnLoad()">
<div id="result"></div>
</body>
</html>
iframe-load.js
var urls = ['file://C:/Users/afrench/Documents/Other/Misc%20Code/Chrome%20iFrame/Doc1.html',
'file://C:/Users/afrench/Documents/Other/Misc%20Code/Chrome%20iFrame/Doc2.html'];
window.addEventListener('message', event => {
'use strict';
var data = event.data;
var container = document.getElementById('container');
window.document.body.removeChild(container);
if (data) {
var resultContainer = document.getElementById('result');
resultContainer.innerHTML += data;
}
if (urls.length > 0) {
OnLoad();
}
})
function OnLoad() {
var url = urls.shift();
if (url) {
var container = document.createElement('div');
container.id = 'container';
container.style.visibility = 'hidden';
window.document.body.appendChild(container);
container.innerHTML = '<iframe src="' + url + '"></iframe>';
}
}
Doc1.html
<!DOCTYPE html>
<html>
<head>
<title>Chrome iFrame Tester</title>
<script>
function OnLoad() {
window.parent.postMessage(window.document.body.innerHTML, '*');
}
</script>
</head>
<body onload="OnLoad()">
<div>This is Doc 1's content!</div>
</body>
</html>

How can I access a variable in Jquery and use its value in another external .js file ? The variable is $generatedP

I need to access in a different .js file the value inside $generatedP and display it
$(document).ready(function() {
var $buttonValue = $(".value_generate");
var $divValue = $(".generated_value");
var $generatedP = $(".generated_p");
var $valueInput2 = $(".value_input_2");
var $submitPages2 = $(".submit_pages_2");
function valueGenerator(value) {
var valueString="";
var lettersNumbers = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
for(var i = 0; i < value; i++)
valueString += lettersNumbers.charAt(Math.floor(Math.random()* lettersNumbers.length));
return valueString;
}//generate string
$buttonValue.click(function generate() {
var $key = valueGenerator(12);
$generatedP.html($key);//display generated string
});
$submitPages2.click(function() {
if($valueInput2.val() == $generatedP.text() ){
alert("you are logged in website");
} else {
alert("please check again the value");
return false;
}//check value if true/false
});
I am new to jquery
You have a few options.
Create a namespace inside the jQuery object:
$.myGlobalNamespace = {};
$.myGlobalNamespace.generatedPvalue = "something";
Define an object at the window level:
window.myGlobalNamespace = {};
window.myGlobalNamespace.generatedPvalue = "something";
Just be sure to use a sensible name for the namespace object.
You can improve the behavior doing client-side checking with localStorage, or you can simply use sessionStorage. Variable $generatedP will be available in page1 and page2. Hope it helps!
PAGE 1:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
</head>
<body>
<script type = "text/javascript">
$(document).ready(function(){
var $generatedP = "27.23.10";
sessionStorage.setItem('myVar', $generatedP);
window.location.href = "page2.html";
});
</script>
</body>
</html>
PAGE 2: to access the variable just use the getItem method and that is all.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<script>
var data = sessionStorage.getItem('myVar');
alert(data);
</script>
</body>
</html>

Jquery .get not retrieving file

i have a code that is supposed to read from a html file, split it into an array and display parts of that array, but when going though with alert, i found that $.get is not actually getting the file
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"> </script>
</head>
<body>
<button onclick="myfunction()">update</button>
<div id="div1"></div>
<script>
function myfunction() {
var info = "";
$.get("../Read_Test/text.html", function(data) {
SomeFunction(data);
});
alert(info);
var array = info.split("§n");
var people = array[1].split(",");
for (var i = 0; i < people.length; i++) {
document.getElementById("div1").innerHTML = people[i] + "<br>";
}
}
function SomeFunction(data) {
var info = data;
}
</script>
</body>
</html>
the directories are on a server and go like so:
Sublinks->Read_Test->This_File.html,text.html
The objective of this is that a file would have something along the lines of "a§nb1,b2,b3,§n" and the script would split it via "§n" then get "array[1]" and split that via ",". lastly it displays each part of that newly created array on a new line, so a file with "a§nb1,b2,b3,§n" would result in:
b1
b2
b3
Please help
Ajax is asynchronous, it make request and immediately call the next instruction and not wait for the response from the ajax request. so you will need to process inside of $.get. success event.
I have changed delimiter character to ¥. change same in text.html. problem was you have not mentioned character set to utf8 and due to this it could not recognized the special character and subsequently not able to split the string. i have aldo document type to HTML5.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
</head>
<body>
<button onclick="myfunction()">update</button>
<div id="div1"></div>
<script>
function myfunction() {
$.get("../Read_Test/text.html", function(data) {
var info = data;
var array = info.split("¥");
var people = array[1].split(",");
for (var i = 0; i < people.length; i++) {
document.getElementById("div1").innerHTML += people[i] + "<br>";
}
});
}
</script>
</body>
</html>

javascript / jquery : problem calling a function inside an object (function undefined)

I'm getting an error of "buildXML is not defined" when I run this code:
var c = {
updateConsumer:function (cid,aid,sid,survey){
var surveyXML = buildSurveyXML(survey);
},
buildSurveyXML: function(survey) {
var surveyResults = survey.split("|");
var surveyXML = '';
for (var i=0;i<surveyResults.length;i++){
...
}
return surveyXML;
}
}
And the html that includes this JS and calls the updateConsumer function:
<!DOCTYPE HTML>
<html lang="en">
<head>
<title>Web Service Test</title>
<meta charset="utf-8">
<script type="text/javascript" src="http://code.jquery.com/jquery-1.6.2.min.js"></script>
<script type="text/javascript" src="../../shared/js/consumerSoap.js"></script>
</head>
<body>
<script type="text/javascript">
$(document).ready(function() {
c.insertConsumer("First","Last","55555","name#url.com","76:1139");
});
</script>
</body>
</html>
The problem is that updateConsumer doesn't know anything about buildSurveyXML; that function isn't in the global scope. However, since your function is part of the same object, you can call it using the this keyword.
updateConsumer:function (cid,aid,sid,survey){
var surveyXML = this.buildSurveyXML(survey);
}
Use
var surveyXML = c.buildSurveyXML(survey);

Categories

Resources