i have this remote web page :
test.html
<html>
<body>
<script>
console.log(5 + 6);
</script>
</body>
</html>
I want to create a script in node.js that can return "11"
I tried to use phantom.js. But, I don't get any result.
var phantom = require('phantom');
phantom.create()
.then(function(ph) {
ph.createPage()
.then(function(page) {
page.open('http://localhost:8888/test.html')
.then(function(status) {
console.log(status);
page.property('onConsoleMessage')
.then(function(content) {
console.log(content);
page.close();
ph.exit();
});
});
});
});
Related
I have a REST API that returns a JSON object like this
{
"id": 1,
"status": "open"
}
where status can be "open" or "closed". I call this API in an HTML page with a JQuery function:
<html>
<body>
</body>
<script>
$(document).ready(function() {
$.getJSON("http://localhost:8080/api/question/1", function(data){
});
});
</script>
If status from returned JSON object is "open", I want to change my HTML page as following
<html>
<body>
<p>THE QUESTION IS OPEN</p>
</body>
<script>
$(document).ready(function() {
$.getJSON("http://localhost:8080/api/question/1", function(data){
});
});
</script>
Otherwise, if status from returned JSON object is "closed", I want to change my HTML page as following
<html>
<body>
<p>THE QUESTION IS CLOSED</p>
</body>
<script>
$(document).ready(function() {
$.getJSON("http://localhost:8080/api/question/1", function(data){
});
});
</script>
What is the best way to achieve this with JQuery?
You can use $('body').prepend() to put the data right after the open <body> tag
$(document).ready(function() {
$.getJSON("http://localhost:8080/api/question/1", function(data) {
if (data.status) {
let str = `The Question is ${data.status}`.toUpperCase()
$('body').prepend(`<p>${str}</p>`)
}
});
});
// for the example
let data = {
"id": 1,
"status": "open"
}
if (data.status) {
let str = `The Question is ${data.status}`.toUpperCase()
$('body').prepend(`<p>${str}</p>`)
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
You have both id and status in your JSON object.
If you are going to have status paragraphs for several questions on the same page, this is the way you could do it:
$(document).ready(
function() {
$.getJSON("http://localhost:8080/api/question/1", function(data) {
let statusParagraph = document.getElementById("status-" + data.id);
let statusText;
if (data.status === "open") {
statusText = "THE QUESTION IS OPEN";
} else if (data.status === "closed") {
statusText = "THE QUESTION IS CLOSED";
}
statusParagraph.innerHTML = statusText;
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<html>
<body>
<p id="status-1"></p>
<p id="status-2"></p>
</body>
</html>
I am running qunit Test using html file in one file and that html file i am running from phantom js.
When I am running html file through browser i am getting output in console but when i am trying to run using phantom js i am not getting the console output in another js file from where i am calling html file.
I am providing both Files:
HTML File :
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>JUnit reporter for QUnit</title>
<link rel="stylesheet" href="qunit.css">
<script src="qunit.js"></script>
<script>
QUnit.config.reorder = false;
</script>
<script src="qunit-reporter-junit.js"></script>
<script src=" http://requirejs.org/docs/release/2.2.0/minified/require.js"></script>
<script>
QUnit.jUnitDone(function(data) {
var console = window.console;
if (console) {
console.log(data.xml);
}
});
</script>
<script src="qunit-reporter-junit.test.js"></script>
</head>
<body>
<div id="qunit"></div>
</body>
</html>
Js file :
var system = require('system');
var fs = require('fs');
var page = require('webpage').create();
if (system.args.length === 1) {
console.log('Pass the path/to/testfile.js as argument to run the test.');
phantom.exit();
} else {
var url = "file:///C:/Users/Admin/Desktop/js/index.html"; // e.g. 'test/unit/tests.html'
console.log("Opening " + url);
}
page.open(url, function (status) {
console.log("Status: " + status);
if (status === "success") {
setTimeout(function () {
var path = 'results.xml';
var output = page.evaluate(function () {
// wants to take console output from html page
.....................................?
});
fs.write(path, output, 'w');
console.log("Wrote JUnit style output of QUnit tests into " + path);
console.log("Tests finished. Exiting.");
phantom.exit();
}, 3000);
} else {
console.log("Failure opening" + url + ". Exiting.");
phantom.exit();
}
});
can anyone suggest me how to take the console output from html file ?
Thanks In Advance.
If your test is similar to this example then to get test results you should request the contents of #qunit-testresult element.
var output = page.evaluate(function(){
return document.getElementById("qunit-testresult").innerText
});
This is my html file:
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<meta http-equiv="Content-Script-Type" content="text/javascript"/>
</head>
<body>
<label for=payload>Payload</label><br>
<textarea id="editor" cols=100 rows=30></textarea><br>
</body>
And the phantomjs script is:
var bodyParser = require('body-parser'),
phantom = require('phantom');
var bk = {"abc":"def"};
//Create Phantom session
var _phSession;
var _page;
var log = console.log;
var config = { logger: { warn:log, info:log, error:log } };
phantom.create([], config).then(function(_session) {
if (_session) {
console.log('Phantom session created');
_phSession = _session;
return _phSession.createPage();
}
})
.then(function(page) {
_page = page;
_page.property('onConsoleMessage', function(msg) {
console.log(msg);
});
_page.property('onLoadStarted', function() {
console.log("load started");
});
_page.property('onLoadFinished', function() {
console.log("load finished");
});
return _page.open("http://myserver/my.html");
})
.then(function(status) {
console.log('Open status:' + status);
if (status != 'success') return;
_page.includeJs('https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js')
.then(function() {
//set the new bkstore
_page.evaluate(function(bk) {
jQuery('#editor').val(JSON.stringify(bk));
return jQuery('#editor').val();
}, bkstore)
.then(function(res) {
console.log('Return from set:' + res);
})
});
setTimeout(function() {
_page.evaluate(function() {
console.log('============== EVALUATE AFTER LOADED ===================');
//return jQuery('#editor').val();
return jQuery('body').html();
})
.then(function(res) {
console.log('html:' + res);
});
}, 1000);
After I set the #editor content with bk, I get back the value I set.
In the block of setTimeout, if I try to get the content of #editor again, I still get back the value of bk.
But I get the html of the body tag, I don't see the value of bk in the #editor.
Anyone knows what the problem is?
I have 3 iframes with reaveal.js presentations. And while they are not on node.js server they.re working perfectly. But I need socket.io to auto-refresh selected iframe when conents of file with reveal.js presentation is changed (I'm uploading a file using php manipulate it and making new .html file with presentation then I'm overwriting the old file).
Node.js server with chokidar is watching for change of file. And it's working.
But everything if failing when I'm joining socket.io and reveal.js together.
Site is constntly refreshing (don't know why i exluded emits) and because of that browser is crashing.
Server code:
var app = require('http').createServer(handler)
var io = require('socket.io')(app);
var fs = require('fs');
var chokidar = require('chokidar');
app.listen(80);
function handler (req, res) {
fs.readFile(__dirname + '/index.html',
function (err, data) {
if (err) {
res.writeHead(500);
return res.end('Error loading index.html');
}
res.writeHead(200);
res.end(data);
});
}
// io.on('connection', function (socket) {
// socket.emit('news', { hello: 'world' });
// socket.on('my other event', function (data) {
// console.log(data);
// });
// });
var watcher = chokidar.watch('file, dir, or glob', {
ignored: /[\/\\]\./, persistent: true
});
watcher.add('prez/prez1.html');
watcher.add('prez/prez2.html');
watcher.add('prez/prez3.html');
var log = console.log.bind(console);
watcher
.on('change', function(path) { log('File', path, 'changed');
//io.emit('restart1');
})
Client code:
<html>
<head>
</head>
<body>
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io('http://localhost');
// socket.on('news', function (data) {
// console.log(data);
// socket.emit('my other event', { my: 'data' });
// });
// socket.on('restart1', function (data) {
// var iframe = document.getElementById('ramka1');
// iframe.src = iframe.src;
// });
// socket.on('restart2', function (data) {
// var iframe = document.getElementById('ramka2');
// iframe.src = iframe.src;
// });
// socket.on('restart3', function (data) {
// var iframe = document.getElementById('ramka3');
// iframe.src = iframe.src;
// });
</script>
<iframe id="ramka1" width="100%" height="33%" src="prez/prez1.html"></iframe><br>
<iframe id="ramka2" width="100%" height="33%" src="prez/prez2.html"></iframe><br>
<iframe id="ramka3" width="100%" height="33%" src="prez/prez3.html"></iframe><br>
<style type="text/css">
iframe {
border:none;
}
</style>
</body>
</html>
Example presentation code:
<html>
<head>
<link rel="stylesheet" href="css/reveal.css">
<link rel="stylesheet" href="css/theme/white.css">
</head>
<body>
<div class="reveal">
<div class="slides">
<section>Slide 1</section>
<section>Slide 2</section>
</div>
</div>
<script src="js/reveal.js"></script>
<script>
Reveal.initialize({controls: false, loop: true, autoSlide: 1000});
</script>
</body>
</html>
i have an html file called room.html.erb which has some js code.when i click on a link it has to load the above page.but the page is loading correctly except js code.when i refresh it working fine.
code in room.html.erb
<script src="http://static.opentok.com/v2/js/opentok.min.js" type="text/javascript"></script>
<script>
var apiKey = xxxxxx;//my apikey
var sessionId ="<%=#group.sessionId%>" ;
var token = "<%=#opentok_token%>";
var session;
OT.setLogLevel(OT.DEBUG);
session = OT.initSession(apiKey,sessionId);
session.on
({
streamCreated: function(event)
{
session.subscribe(event.stream,'subscribersDiv',{insertMode: 'append'});
}
});
session.connect(token,function(error){
if(error)
{
console.log(error.message);
}
else{
session.publish('myPublisherDiv',{width: 320,height: 240});
}
});
</script>
i couldn't able to figure it out why it is happening.
Wait until the DOM is loaded?
<script src="http://static.opentok.com/v2/js/opentok.min.js" type="text/javascript"></script>
<script type="text/javascript">
document.addEventListener("DOMContentLoaded", function(event) {
var apiKey = xxxxxx;//my apikey
var sessionId ="<%=#group.sessionId%>" ;
var token = "<%=#opentok_token%>";
var session;
OT.setLogLevel(OT.DEBUG);
session = OT.initSession(apiKey,sessionId);
session.on
({
streamCreated: function(event)
{
session.subscribe(event.stream,'subscribersDiv',{insertMode: 'append'});
}
});
session.connect(token,function(error){
if(error)
{
console.log(error.message);
}
else{
session.publish('myPublisherDiv',{width: 320,height: 240});
}
});
});
</script>
another method
add
<div id="myPublisherDiv"></div>
<div id="subscribersDiv"></div>