How get information from variable web page with use node.js? - javascript

There is a web page. In page source have script:
<script>
var important = [{....}];
</script>
How get information from this variable with use node.js???
In a similar situation, when information was in function:
$(function() {
_very.important ([{....}]);
I use code:
var cloudscraper = require("cloudscraper");
cloudscraper.get("link" , function(error, response, data) {
if (error) {
console.log('ERRRRRRROR');
} else {
var info = JSON.parse(data.split("_very.important(")[1].split(")")[0]);
But, I dont know how work with this problem.
var important = [{....}];

You can assign a id to the script like <script id="script"> and get the details through innerHTML like
document.getElementById('script').innerHTML

Related

Pass data between two HTML pages (Google Apps Script)

I'm trying to pass var 'id' from the page 'a.html' to 'b.html'. The var content comes from 'code.gs' as below:
code.gs
function data(){
var id = 1;
return id;
}
Next, I get this var and I show it in 'a.html':
a.html
<?
var id = data();
?>
<h1><?= id ?></h1>
Go to B.html
By clicking 'Go to B.html', the system directs the user to there. I need to bring the same value of var 'id' from the page 'a.html' to 'b.html'.
Ps: searching for a little, I saw that there's a kind to send this var by the command 'localStorage', but it's not working for me. :(
Can anybody help me?
Use localstorage
a.html
localStorage.setItem('id',1)
b.html
var id = localStorage.getItem('id')
the other way is to put it in a js file and import it in both html
Storing & Retrieving html data on the server
Client Side JavaScript:
<script>
function saveId(v) {
google.script.run.saveKeyValue({key:'id',value:v});
}
function getId() {
google.script.run
.withSuccessHandler(function(v){
alert('The value is ' + v );
})
.getKeyValue('id');
}
</script>
Server Side Google Apps Script:
function saveKeyValue(obj) {
PropertiesService.getScriptProperties().setProperty(obj.key,obj.value);
}
function getKeyValue(key) {
return PropertiesService.getScriptProperties().getProperty(key);
}
You could also replace PropertiesService with CacheService.
Client To Server Communications
Properties Service

how to consume data from response.write

I am opening an html page with the code below. I am also sending is data to that page with the response.write() function:
fs.readFile('./calc.html', function(error, data){
if(error){
//do nothing for now
} else if (data){
resp.writeHead(200, {'Content-Type':'text/html'});
var sum = 9;
resp.write(sum);
resp.end(data);
}
});
How do I consume the value from 'sum' in calc.html when the page opens? In the script tag in the , I'm utilizing the Window.onload method to perform an action when the page loads. The number 9 appears in the top left hand corner of the web page when it loads, so I konw it's there, I just dont know how to consume it and use it.
<script type="text/javascript">
var htmlSum = 0;
function fetchData() {
htmlSum = //How to I scrape the 'sum' variable sent into the page?????
}
window.onload = fetchData;
</script>
What you're writing here gets received as an HTML page (in this case), which is why it just displays the number "9" in the browser. If you package it inside a <script> tag it will be available as JS:
resp.writeHead(200, {'Content-Type':'text/html'});
var sum = 9;
resp.write('<script type="text/javascript">var mySumVar = ' + sum + ';</script>');
return resp.end(data); //the "return" doesn't change anything,
//but it's good practice to make sure the function ends here
...And you can then access mySumVar from your other clientside scripts. Note that this will go in the global scope, which makes it easier to access but also bad practice. You may want to package it inside some other object to avoid polluting the scope.
Instead of writing the number at the top of the page, you can write placeholders that will be replaced with your data. For example, you could use {{sum}} as a placeholder and replace {{sum}} with your sum:
fs.readFile('./calc.html', function(error, data){
if(error){
//do nothing for now
} else if (data){
resp.writeHead(200, {'Content-Type':'text/html'});
var sum = 9;
resp.end(data.replace("{{sum}}", sum);
}
});
and in your html..
<script type="text/javascript">
var number = 0;
function fetchData() {
number = {{sum}};
}
window.onload = fetchData;
</script>
If you are planning to include more logic from the serverside into your webpage, I would recommend you look into a template engine such as EJS.

Flaskr url_for with javascript variable as parameters is not working to python

I'm trying to use flask with url_for. The problem is that when I try to launch an alert with the value of the javascript variable everything seems ok, but when I try to launch a alert with the url_for the content of the variable is not printed. What I'm doing wrong? or What is missing in my code?
How can I pass a JavaScript variable into the url_for function?
html code:
<a class="dissable_user_btn" data-user_id="{{user.id}}" href="#" title="Change Status"><i class="fa fa-plug"></i>
</a>
JS Code:
<script type="text/javascript">
$(document).ready(function(){
$('.dissable_user_btn').click(function( event ) {
var user_id = $(this).data("user_id")
alert(user_id) //everything ok
alert ('{{url_for('.dissable', _id=user_id)}}'); //dont print the valur of user_id
</script>
Short answer: you can't. Flask & Jinja2 render the template on the server side (e.g. Flask is translating all of the {{ }} stuff before it sends the HTML to the web browser).
For a URL like this where you're including a variable as part of the path you'd need to build this manually in javascript. If this is an XHR endpoint I'd recommend using GET/POST to transfer the values to the server as a better best practice than constructing the URL this way. This way you can use Jinja:
$(document).ready(function(){
var baseUrl = "{{ url_for('disable') }}";
$('.dissable_user_btn').click(function(event) {
var user_id = $(this).data("user_id");
// first part = url to send data
// second part = info to send as query string (url?user=user_id)
// third parameter = function to handle response from server
$.getJSON(baseUrl, {user: user_id}, function(response) {
console.log(response);
});
});
});
I found another solution for this. My problem started when I needed to pass a variable with space.
First I created a function to remove trailing and leading spaces
function strip(str) {
return str.replace(/^\s+|\s+$/g, '');}
After that, I used the function and encoded the URL
<script type="text/javascript">
$(document).ready(function(){
$('.dissable_user_btn').click(function( event ) {
var user_id = $(this).data("user_id")
alert(user_id)
user_id = strip(user_id).replace(" ","%20");
alert ('{{url_for('.dissable', _id='user_id')}}.replace('user_id',user_id);
</script>
It worked pretty nice for me!
This is how I applied to my problem
<script>
function strip(str) {
return str.replace(/^\s+|\s+$/g, '');}
$(document).ready(function() {
$('#exportcountry').click(function() {
var elemento = document.getElementById("countryexportbtn");
var country = strip(elemento.textContent).replace(" ","%20");
$('#exportevent').load("{{ url_for('get_events',country = 'pais') }}".replace('pais',country));
});
});
</script>

obtain "server side" variable for use in html/javascript function

I'm trying to develop a language web application. It will scrape data from various websites and ask the participant numerous questions etc. I have created the file that scrapes the web page but I'm having difficulty getting the scraped variables from the node.js file. below are some extracts from the node js file:
var pword = function() {
var request = require("request");
var cheerio = require("cheerio");
var aa = Math.floor(Math.random() * 588);
var words = ['abash', 'aberrant', .....]
var A = words[aa];
var urlcollinsdictionary = "http://www.collinsdictionary.com/dictionary/english/";
var Newurldictionary = urlcollinsdictionary + A;
request({
uri: Newurldictionary,
}, function(error, response, body) {
var $ = cheerio.load(body);
$('div.homograph-entry').each(function() {
var link = $(this);
var text1 = link.text();
console.log(A);
console.log(text1);
});
});
}
My node js code works fine. my problem arises when I try to use its "text1" variable or others of its kind in my HTML/javascript coding. I've tried "getelementbyid", "variable exports/imports", even the "%%" method. but still no luck. as you've probably get guess I'm new to programming. please please please help me by making alterations/additions to the HTML code beneath to enable access to the text1 variable and others like it
<html>
<head>
language game
<title>language game</title>
<br>
<input type = "button" onclick = "word()" value = "Professional Vocab">
</head>
<body>
<script>
function word(){
alert(text1);
}
</script>
</body>
</html>
Thanks in advance...
You can add similar code in your node js file to respond to api calls
var express = require("express");
var app = express();
app.get("sendVar", function(request, response){
response.send(text1);
}
you will need to do npm install express in your command line
In your front-end side you can use jquery and make an AJAX call inside function word()
function word(){
$.get("url/sendVar", function(data){
alert(data);
});
}

Update multiple div from json file every sec without page flicker

I wrote the script below to get values from a Json file that is stored inside a industrial automation equipment. The script is inside a HTML page that is stored in a PC and replaces Div contents based on its ID. Note: I can't run any code on the industrial equipment. This is not a "real server". It just stores Json files and update its values based in real sensors.
Script inside index.html
<script>
function callback(json)
{
document.getElementById("Nro_Ensaio").innerHTML = json.Nro_Ensaio;
document.getElementById("SP_Pelotas1").innerHTML = json.SP_Pelotas;
document.getElementById("SP_Pelotas2").innerHTML = json.SP_Pelotas;
document.getElementById("PV_Pelotas1").innerHTML = json.PV_Pelotas;
document.getElementById("Status").innerHTML = json.Status;
}
</script>
<script type="text/javascript" src="http://192.168.0.103/awp/VAR_PRENSAS/ensaio.json"></script>
ensaio.json file
callback({
'Inicia': ':="ENSAIO".CMDS.LIBERA:',
'Rearme': ':="ENSAIO".CMDS.RESET:',
'Nro_Serie': ':="ENSAIO".Nro_Serie:',
'Modelo': ':="ENSAIO".Modelo:',
'Nro_Ensaio': ':="ENSAIO".Nro_Ensaio:',
'Pronto': ':="ENSAIO".Pronto:',
'Data': ':="ENSAIO".Data:',
'Hora': ':="ENSAIO".Hora:',
'SP_Pelotas': ':="ENSAIO".SP_Pelotas:',
'PV_Pelotas': ':="ENSAIO".PV_Pelotas:',
'Status': ':="ENSAIO".Status:'
});
When I open index.html in a browser I can view all values on the places that I really want, but I need a way to get this values refreshed. I tried to refresh the page using the script below, but div values flickers every time.
<script type="text/JavaScript">
<!--
function timedRefresh(timeoutPeriod) {
setTimeout("location.reload(true);",timeoutPeriod);
}
// -->
</script>
</head>
<body onload="JavaScript:timedRefresh(5000);">
How can I update div contents from the Json file every second without flickering the page?
Very important Information: I can't enable cross-domain requests on this "server".
More information about creating pages for this equipment here! http://www.dmcinfo.com/latest-thinking/blog/articletype/articleview/articleid/8567/siemens-s7-1200-web-server-tutorial--from-getting-started-to-html5-user-defined-pages
Thanks!
I tryed to do this script below.
<script>
function callback(json)
{
document.getElementById("Nro_Ensaio").innerHTML = json.Nro_Ensaio;
document.getElementById("SP_Pelotas1").innerHTML = json.SP_Pelotas;
document.getElementById("SP_Pelotas2").innerHTML = json.SP_Pelotas;
document.getElementById("PV_Pelotas1").innerHTML = json.PV_Pelotas;
document.getElementById("Status").innerHTML = json.Status;
}
setInterval(callback,1000);
</script>
<script type="text/javascript" src="192.168.0.103/awp/VAR_PRENSAS/ensaio.json"></script>
Ensaio.json Content
callback({
'Inicia': '0',
'Rearme': '0',
'Nro_Serie': '010',
'Modelo': 'CPT001',
'Nro_Ensaio': '138',
'Pronto': '0',
'Data': '18-07-2014',
'Hora': '10-02',
'SP_Pelotas': '40',
'PV_Pelotas': '1',
'Status': 'ENSAIO',
'Nome': 'Test',
'Descricao': 'Test1'
});
I tried changing the src attribute of the script tag in Javascript, but it seems as though the script tag needs to be replaced for the script to load. Here's a function that takes a script URI and an interval and then reloads the script indefinitely, without piling up a bunch of script tags:
var scriptLoader = (function () {
var head = document.getElementsByTagName("head")[0];
return function (scriptURI, interval) {
var scriptElement = null;
setInterval(function () {
var newScriptElement = document.createElement('script');
newScriptElement.type = 'text/javascript';
newScriptElement.onerror = function (error) {
throw new URIError('Could not load script ' + error.target.src);
};
if (scriptElement) {
head.replaceChild(newScriptElement, scriptElement);
} else {
head.appendChild(newScriptElement);
}
newScriptElement.src = scriptURI;
scriptElement = newScriptElement;
}, interval);
}
}());
It's used like this:
window.onload = function () {
scriptLoader("http://192.168.0.103/awp/VAR_PRENSAS/ensaio.json", 10000);
};
[EDIT: this answer is only valid if you can set Access-Control-Allow-Origin headers on your server. also, my answer is sans jquery.]
if i understand you correctly, the name for what you are trying to do is asyncronous http requests. that means that you want to get more information from a server without reloading the whole page. the javascript technology that is used to do so is called ajax or XHR. here is an example of how to use ajax. you will want to replace the URL in xmlhttp.open("GET","ajax_info.txt",true); with the (complete) URL of the file on the server you want to access, i.e. http://..... the response that your requests gets from the server is stored in xmlhttp.responseText where xmlhttp is the name of the variable assigned to the ajax request.
[EDIT: in light of new information, maybe you'd prefer reloading an iframe than the whole page? not an awesome solution but iframes don't require cross-site request.]

Categories

Resources