PhantomJS' require failed to load in browser - javascript

Here is my code :
<html>
<body>
<script src="bin/phantomjs"></script>
<script src="js/test.js"></script>
</body>
</html>
inside test.js
var page = require('webpage').create();
console.log('The default user agent is ' + page.settings.userAgent);
page.settings.userAgent = 'SpecialAgent';
page.open('http://www.httpuseragent.org', function (status) {
if (status !== 'success') {
console.log('Unable to access network');
} else {
var ua = page.evaluate(function () {
return document.getElementById('myagent').innerText;
});
console.log(ua);
}
phantom.exit();
});
I got these error when viewed using Chrome.
Uncaught SyntaxError: Unexpected token ILLEGAL
test.js:1 Uncaught ReferenceError: require is not defined
I wanted to load PhantomJS in my html project, so that I can begin to scrape websites.

PhantomJS is a standalone application/browser that takes a script written in JavaScript and drives a headless browser component. You can't load that script into a browser and drive either PhantomJS or the browser it is executed in with that script. It is comparable with node.js in that you can't simply run node.js scripts in the browser. Note that node.js and PhantomJS have different execution environments.
If you want to trigger a PhantomJS script from a client-browser, you would make an HTTP request from the client browser to your server, where you would call the PhantomJS script through exec() or something similar in your favorite server framework/language, compute the result on the server and send it back to the client.

Related

Fetch request returns html/text instead of JSON content when launched from Nodejs server [duplicate]

I'm starting with Node.js and I have already a problem in my first program. Below is the code I'm using. Index.html:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Random Temperatures</title>
</head>
<body>
<input type="text" id="tb" name="tb" />
<input type="button" value="Random Number!" id="myButton" name="myButton"/>
<script src="client.js"></script>
</body>
</html>
Client.js:
const textBox = document.getElementById('tb');
const button = document.getElementById('myButton');
button.addEventListener('click', function(e) {
var rnd = Math.floor(Math.random() * 100);
textBox.value = rnd;
});
Server.js:
var app = require('http').createServer(response);
var fs = require('fs');
app.listen(8080);
console.log("App running…");
function response(req, res) {
fs.readFile(__dirname + '/public/index.html',
function (err, data) {
if (err) {
res.writeHead(500);
return res.end('Failed to load file index.html');
}
res.writeHead(200);
res.end(data);
});
}
When I start the application I go to the browser the text box and the button appear. But in the browser console I'm getting these errors:
client.js:1 Uncaught SyntaxError: Unexpected token <
ContentScript.js:112 Exception in onResRdy: TypeError: Cannot read
property 'htmlRes' of undefined
localhost/:1 Unchecked runtime.lastError: Could not establish
connection. Receiving end does not exist.
I guess my problem is the linking between the 3 files but I tried several things and I can't solve the problem. I'm sure it's a stupid error but forgive me I'm just getting start. Any advice?
The browser (because you have <script src="/client.js">) makes a request for /client.js
The server:
Gets the request
Runs response
Reads index.html
Sends it to the browser
Since index.html starts with <, the browser throws an error when it tries to run it as JavaScript.
Why are you giving the browser index.html when it asks for client.js?
You need to examine the request object, determine what URL is being asked for, write logic to return the correct resource with the correct status code and the correct content-type, and then return that to the client.
The Node.js documentation has an example of this but you should probably stop trying to use createServer directly — since it involves a massive amount of wheel reinvention — switch to using Express and work through the (very short) getting started guide which includes a section on using the static module to serve up static files.

Service worker runs in browser (chrome) but fails to register in Android WebView?

So currently, i'm working with an app that is written in react and has a service worker script. It is rendered on a Honeywell CT40 device via an Android hardware abstraction layer through a webview in the android/java code. Everything seems to work fine in the chrome browser when running the react app only. However, when the android app runs and renders the app, the service worker fails to register. The only error message I get on the chrome logs are:
Uncaught DOMException: Failed to execute 'importScripts' on 'WorkerGlobalScope': The script at 'https://storage.googleapis.com/workbox-cdn/releases/5.1.2/workbox-sw.js' failed to load.
This error only occurs when visiting the app through the android app via webview, but when using the browser directly, no issues.
Any thoughts?
WebView version: 79.0.3945.116
WebView version: com.android.chrome
Again, this works as expected in the browser itself, just not in the android webview browser it seems. Any idea? Attached are screenshots. Below is a code sample of where the service worker script starts. As stated in the documentation here: https://developer.chrome.com/docs/workbox/modules/workbox-sw/
/* eslint-disable */
importScripts(
'https://storage.googleapis.com/workbox-
cdn/releases/5.1.2/workbox-sw.js'
);
let window = self
importScripts('/__ENV_FILE__.js')
workbox.setConfig({
debug: window.$$.APP_WORKBOX_CONFIG_DEBUG || false
})
const { precacheAndRoute, createHandlerBoundToURL } = workbox.precaching
const { NavigationRoute, registerRoute } = workbox.routing
const { NetworkOnly } = workbox.strategies
const { Queue } = workbox.backgroundSync
// Injection point of precache assets
precacheAndRoute(self.__WB_MANIFEST)
self.addEventListener('message', (event) => {
if (event.data && event.data.type === 'SKIP_WAITING') {
self.skipWaiting()
}
})
error 1
error 2

AngularJS and Web API :- net::ERR_CONNECTION_REFUSED in chrome and error 00002efd in IE

There are lots of question like my question but I didn't any working solution.
I am using AngularJS and WebApi2 in my application.
Here is the JS code which call the initial API.
(function (module) {
var baseUrl= "http://localhost:85";
module.constant('Config', baseUrl);
module.service('identities', ['$http', function ($http) {
var uri = baseUrl+ '/api/controller/GetRole';
var identities = {};
identities.get = function () {
var temp = $http.get(uri);
console.log(temp, "identities");
return temp;
}
return identities;
}]);
This function call the GetRole method in web API controller to retrieve user role.The output of this method is JSON with user details.
I have deployed the application on a server to port 85. When I run the application it's throwing error in Chrome:
net::ERR_CONNECTION_REFUSED
and in IE 11:
XMLHttpRequest: Network Error 0x2efd, Could not complete the operation due to error 00002efd
There is no log created in IIS for this request.
Using fiddler I got this in Raw with status code 502 in response.
The connection to 'localhost' failed.
Error: ConnectionRefused (0x274d).
System.Net.Sockets.SocketException No connection could be made because the target machine actively refused it 127.0.0.1:85.
I have also tried by disabling the CORS in chrome but no luck.
IF I use IP address of server instead of localhost as baseUrl in angular JS code then it's working fine.
Why it's not working with localhost?
I am doing a GET call and Error for me is 00002efd not 00002ef3.

SignalR not hitting OnConnected and giving Newtonsoft.Json.JsonReaderException

I am trying to setup SignalR at my ASP.NET MVC site and a Javascript client.
This is my client:
#section scripts{
<script src="~/Scripts/jquery.signalR-2.0.2.min.js"></script>
<script type="text/javascript">
$(function () {
var connection = $.connection('/MY_ENDPOINT');
connection.received(function (data) {
$('#chatArea').append('>>' + data + "\r\n");
});
connection.start().done(function () {
$("#send").click(function () {
connection.send($('#msg').val());
$("#msg").val("");
});
});
connection.error(function (e) {
console.log(e);
});
});
</script>
}
Of course, I have the corresponding HTML elements chatArea and msg. In server, here is what I did:
Installed SignalR (latest version currently, 2.0.2) through NuGet.
Added app.MapSignalR("MY_ENDPOINT", new Microsoft.AspNet.SignalR.HubConfiguration()); in startup configuration, made sure it is called before registering auth methods.
I've subclassed PersistentConnection and overridden OnConnected and OnReceived methods.
However, when I run my app and navigate to the page, I can see that my endpoint's negotiate and connect methods are called, they both return OK (HTTP 200). I try to send anything using the webpage by clicking the "send" button, and at the server side I'm getting this error:
A first chance exception of type 'Newtonsoft.Json.JsonReaderException'
occurred in Newtonsoft.Json.dll
Additional information: Unexpected character encountered while
parsing value: a. Path '', line 0, position 0.
What could be the cause of this error?
UPDATE: I also have an iOS app with the SignalR-ObjC framework, and I can connect. However, when I try to send any data over it, I'm getting:
2014-03-06 19:39:39.853 Tanisalim[54987:70b] Websocket error: Error Domain=AFNetworkingErrorDomain Code=-1011 "Request failed: internal server error (500)" UserInfo=0xade84e0 {NSErrorFailingURLKey=http://10.211.55.3/api/socket/send?transport=longPolling&connectionData=(null)&connectionToken=xybYQ8ItTN0IWUbyrosuHy%2F3jN0krIyHLO6b6Gq8VdC3orwRRGkVSIgtYkNQINVLhRMW77cX%2BU2LiHxoe0eDE3ZumT7JrObJcQ%2FXyHiP25%2BQy%2BZizHEHbsPyBBomERoI, NSLocalizedDescription=Request failed: internal server error (500), NSUnderlyingError=0xade1290 "Request failed: unacceptable content-type: text/html"
Still, no server-side breakpoints are hit.

error on connecting to the server : socket io is not defined

i know there's been couple of question about the same problem , i've already check them .
i have very simple node.js chat app
i have a server running on 8000 port and it works fine
my client pages are html , they are running on apache and i'm using socket.io to connect them to the server and it works fine on the local host
but when i upload the app on the server i keep on getting this error in the firebug
io is not defined
var socket = io.connect('http://atenak.com:8000/');
or sometimes it doesn't show that but when i try to broadcast message from cliend i get this error :
socket is undefined
socket.emit('msg', { data: msg , user:'max' });
the only difference is i've changed the localhost with atenak.com !
here is my html code
var socket = io.connect('http://atenak.com:8000/');
var user = 'jack';
socket.on('newmsg', function (data) {
if(data.user == user )
{
$('#container').html(data.data);
}
});
function brodcast(){
var msg = $('#fild').val();
socket.emit('msg', { data: msg , user:'max' });
}
</script>
</head>
<body>
<div id="container"> </div>
<input id="fild" type="text"> <input name="" type="button" onClick="brodcast();">
</body>
i have included the sockt.io.js
src="http://atenak.com:8000/socket.io/socket.io.js"
and server is running ok which means socket.io is installed on the server
here is the live page
http://atenak.com/client.html
I'm getting:
> Uncaught ReferenceError: io is not defined client.html:7
x GET http://atenak.com:8000/socket.io/socket.io.js
indicating that your page cannot load http://atenak.com:8000/socket.io/socket.io.js; indeed, if you try to load that URL in the browser, you get a connection error. Make sure that your Node.js server (running Socket.IO) is accessible (e.g. ports not being blocked by a firewall, etc).
Seems port 8000 is not open on your host as per links below
Reverse ip check for atenak.com and Open port check
Socket.io need a javascript file and this file does not load correctly.
Here is the url: http://atenak.com:8000/socket.io/socket.io.js
In this file is defined the îo object.

Categories

Resources