Passing value to target webpage using phantomjs - javascript

I am using Phantomjs. I need to pass certain information to the webpage (http://localhost:4569/index.html) we are targeting. The idea is, as soon as the target page loads, pass a JSON object to page & set it a globally accessible variable. Something like window.data = {....}. Once this variable is set, the target page will make use of this variable. Is it possible to get the desired result using Phantomjs?
var webPage = require('webpage');
var page = webPage.create();
var settings = {
operation: "POST",
encoding: "utf8",
headers: {
"Content-Type": "application/json"
},
data: JSON.stringify({
some: "data",
another: ["custom", "data"]
})
};
page.open('http://localhost:4569/index.html', settings, function(status) {
console.log('Status: ' + status);
//

One way that you might be able to facilitate this is a combination of setInterval and injectJs(). I would check for the data in the target page every few seconds. Then I would inject in a piece of data using injectJs. Then I would digest the injected data and have the phantomjs script react accordingly.
index.html
<html>
<head>
<title>Phantest</title>
</head>
<body>
<main>
<h1>Phantom Test</h1>
<p>Test of phantom</p>
</main>
<script>
(function () {
console.log("Hello");
setInterval(function () {
if (window.myVar) {
console.log("window.myVar is here!");
console.log(window.myVar);
}
}, 1000);
}());
</script>
</body>
</html>
phan.js
/*jslint node:true*/
"use strict";
var page = require("webpage").create();
page.onConsoleMessage = function (msg) {
console.log(msg);
};
page.open("http://127.0.0.1:52987/index.html", function (status) {
if (status === "success") {
page.injectJs("inject.js");
}
});
inject.js
/*jslint browser:true devel:true*/
console.log("I'm from Phantom");
window.myVar = "I'm myVar!";

Related

Use template variable as part of script src

I am trying to create a model payments popup where the user can upgrade their plan in a google apps script. In my .gs file I have:
function manageSubscription() {
var title = 'subscribe';
var html = HtmlService.createTemplateFromFile('subscribe');
html.email = Session.getActiveUser().getEmail();
var htmlOutput = html.evaluate();
htmlOutput.setTitle(title).setWidth(200).setHeight(200)
DocumentApp.getUi().showModalDialog(htmlOutput, title);
}
In my .html file, I am trying to use that email address to pass it to paypal when they signup:
<script id="paypal_js"></script> // how do I set the src???
<script>
$(document).ready(function(){
var src = 'https://www.paypal.com/sdk/js?client-id=my-client-id&email=';
document.getElementById('paypal_js').src = src+<?= email ?>;
paypal.Buttons({
createSubscription: function(data, actions) {
return actions.subscription.create({'plan_id': 'P-my-plan'});
},
onApprove: function(data, actions) {
google.script.host.close();
}
}).render('#paypal-button-container');
});
</script>
However, I get ReferenceError: paypal is not defined in the browser console. Oddly, I can do a simple 'alert();' and see that I am getting the email.
The problem is with your code where use are using paypal,
You are dynamically adding script and I assume, you will be getting paypal as global object from this script.
What you forgot is, at the time of your code execution of paypal.Buttons, paypal is not available in browser. Since, it's still probably fetching and evaluating code from script, you just included. You have to listen to script onload event and call your required functions after that.
<script id="paypal_js"></script> // how do I set the src???
<script>
$(document).ready(function(){
var src = 'https://www.paypal.com/sdk/js?client-id=my-client-id&email=';
var scriptTag = document.getElementById('paypal_js')
scriptTag.src = src+<?= email ?>;
scriptTag.onload = function() {
paypal.Buttons({
createSubscription: function(data, actions) {
return actions.subscription.create({'plan_id': 'P-my-plan'});
},
onApprove: function(data, actions) {
google.script.host.close();
}
}).render('#paypal-button-container');
}
});
</script>

Sending messages with Websockets

I have the following html/javascript code that uses websockets to communicate with a server. It seems like I can only send(message) only inside the onmessage() and onopen() functions. How can I send data outside of those functions ?
<!DOCTYPE HTML>
<html>
<head>
<script type="text/javascript">
function WebSocketTest() {
if ("WebSocket" in window) {
var ws = new WebSocket("ws://localhost:57252/");
ws.onopen = function () {
ws.send("Hi, from the client."); // this works
alert("Connection opened...");
};
ws.onmessage = function (event) {
alert("Message received..." + event.data);
};
ws.onclose = function () {
alert("Connection closed...");
};
ws.send("Hi, from the client."); // doesn't work
ws.send("Hi, from the client."); // doesn't work
}
}
</script>
</head>
<body>
<div id="sse">
Run WebSocket
</div>
</body>
</html>
You are probably experiencing a race condition where you try to perform a send command even though the socket may not have been opened yet. There's an important note on the MDN that describes this behavior:
As establishing a connection is asynchronous and prone to failure there is no guarantee that calling the send() method immediately after creating a WebSocket object will be successful.
You, essentially, are calling the send method immediately after creating a WebSocket.
If you move that logic to a function and call that function when you know the connection has been open, you might be fine. For example, try moving the code into a timeout or another function that can be manually triggered after you know the socket connection has been established:
function sendMyMessages() {
ws.send("Hi, from the client.");
ws.send("Hi, from the client.");
}
<button onclick="sendMyMessages()">Test</button>
Because onopen is an asynchronous event.
It's similar to doing this:
var value;
$.ajax({
url: '/post/data',
success: function(response) {
value = response;
}
});
alert(value);
What do we get in the alert? undefined.
The websocket works in a similar manner, you cannot send until the connection has finished opening. It opens asynchronously. Therefore, anytime you try to use send, you must ensure that the connection is already open. Right now, you are trying to synchronously use those send calls, before the connection is actually open.
This is the html file of Sanic webserver websocket demo.
<!DOCTYPE html>
<html>
<head>
<title>WebSocket demo</title>
</head>
<body>
<script>
var ws = new WebSocket('ws://' + document.domain + ':' + location.port + '/feed'),
messages = document.createElement('ul');
ws.onmessage = function (event) {
var messages = document.getElementsByTagName('ul')[0],
message = document.createElement('li'),
content = document.createTextNode('Received: ' + event.data);
message.appendChild(content);
messages.appendChild(message);
};
document.body.appendChild(messages);
window.setInterval(function() {
data = 'bye!'
ws.send(data);
var messages = document.getElementsByTagName('ul')[0],
message = document.createElement('li'),
content = document.createTextNode('Sent: ' + data);
message.appendChild(content);
messages.appendChild(message);
}, 1000);
</script>
</body>

How to send a cross-domain POST request using ajax call in c#

I am developing an application in which from a website project I give a call to web api method using ajax call javascript. When I run both projects locally it works fine, but when I do publish web api project on demo site the ajax call does not reach to the web api method.
My ajax call is as follows-
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<title></title>
<script type="text/javascript">
$(document).ready(function () {
var url = 'http://abc.demo.in/c60/api/Patient/Create/';
$.ajax({
url: url,
data: getData(),
type: 'POST',
contentType: "application/json",
success: function (result) {
console.log(result);
alert("success")
},
error: function (result) {
alert('POST failed.');
}
});
function getData() {
var patient = new Object();
patient.Name = "Mugdha";
patient.Gender = "Female";
patient.Email = "mugdhaShenoy#yahoo.co.in";
patient.Mobile = "";
patient.BloodGroup = "AB+";
patient.MedicalHistory = "High BP, Cholosterol, Diebetis";
patient.Allergy = "Dust, wind";
patient.EmergencyContactName = "Riya Sahani";
patient.EmergencyContactNo = "9988990200";
patient.ProfileImage = "";
patient.FormNo = "92";
patient.BirthDate = new Date(1989, 09, 08).toISOString();
return patient;
}
</script>
</head>
<body>
</body>
</html>
When I try to reach the api domain(which is on different server) I have faced an error as -
XMLHttpRequest cannot load http://abc.demo.in/c60/api/Patient/Create/. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:49370' is therefore not allowed access.
Is there any solution for this? I have added CorsHandler.cs file in my webapi project.

Unsafe JavaScript attempt to access frame with URL when using Twitter/Facebook

I am building a website using the Twitter and Facebook JavaScript SDKs. I am attempting to perform tweets and facebook shares from the site. But I am getting the following error when I try to send a tweet OR facebook share from my website:
Chrome:
Unsafe JavaScript attempt to access frame with URL http://edro.no-ip.org:3000/#_=_ from frame with URL http://platform.twitter.com/widgets/tweet_button.1354761327.html#_=1355186876357&count=none&id=twitter-widget-0&lang=en&original_referer=http%3A%2F%2Fedro.no-ip.org%3A3000%2F%23_%3D_&related=xbox%3AGhostfire%20Games&size=m&text=Check%20out%20this%20fun%20story!%20%23atalltale&url=http%3A%2F%2Fedro.no-ip.org%3A3000%2Fstories%2FiqU9xW1FJI. The frame requesting access set 'document.domain' to 'twitter.com', but the frame being accessed did not. Both must set 'document.domain' to the same value to allow access.
Safari:
Unsafe JavaScript attempt to access frame with URL http://edro.no-ip.org:3000/ from frame with URL http://platform.twitter.com/widgets/tweet_button.1354761327.html#_=1355197702032&count=none&id=twitter-widget-0&lang=en&original_referer=http%3A%2F%2Fedro.no-ip.org%3A3000%2F&related=xbox%3AGhostfire%20Games&size=m&text=Check%20out%20this%20fun%20story!%20%23atalltale&url=http%3A%2F%2Fedro.no-ip.org%3A3000%2Fstories%2FiqU9xW1FJI. Domains, protocols and ports must match.
Here's the code (I only included the relevant parts):
<!DOCTYPE html><html xmlns="http://www.w3.org/1999/xhtml" xmlns:fb="https://www.facebook.com/2008/fbml">
<head>
<title>Title</title>
<link rel="stylesheet" href="/stylesheets/style.css">
</head>
<body>
</body>
<center>
<h1>Page Header</h1>
&nbsp
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>
<div id="fb-root"></div>
<script type="text/javascript">
// Once the Facebook SDK is fully loaded, this callback will be invoked
window.fbAsyncInit = function()
{
FB.init({
appId: "250634021702621",
status: true,
cookie: true,
channelUrl: '//edro.no-ip.org:3000/channel.html',
});
FB.Event.subscribe('auth.statusChange', handleStatusChange);
};
// Callback for once we are logged in and authorized
function handleStatusChange(response) {
document.body.className = response.authResponse ? 'connected' : 'not_connected';
if (response.authResponse)
{
}
};
// Declare a generic SDK loading function
var loadSDK = function(doc, script, id, src)
{
var js, fjs = doc.getElementsByTagName(script)[0];
if (!doc.getElementById(id))
{
js = doc.createElement(script);
js.id = id;
js.src = src;
js.async = true; // Makes SDK load asynchronously
fjs.parentNode.insertBefore(js,fjs);
}
};
// Twitter SDK loading
loadSDK(document, 'script', 'twitter-wjs', 'https://platform.twitter.com/widgets.js');
// Facebook SDK loading
loadSDK(document, 'script', 'facebook-jssdk', '//connect.facebook.net/en_US/all.js');
// Facebook callback - useful for doing stuff after Facebook returns. Passed as parameter to API calls later.
var myResponse;
function callback(response)
{
if (response)
{
// For debugging - can query myResponse via JavaScript console
myResponse = response;
if (response.post_id)
{
}
else
{
// Else we are expecting a Response Body Object in JSON, so decode this
var responseBody = JSON.parse(response.body);
// If the Response Body includes an Error Object, handle the Error
if(responseBody.error)
{
}
// Else handle the data Object
else
{
}
}
}
}
// All API calls go here
$(document).ready(function ()
{
// Post to your wall
$('#post_wall').click(function ()
{
FB.ui(
{
method: 'feed',
// useful if we want the callback to go to our site, rather than the JavaScript, so we can log an event
redirect_uri: 'http://edro.no-ip.org:3000',
link: 'http://edro.no-ip.org:3000/stories/{game.id}',
picture: 'http://fbrell.com/f8.jpg',
name: 'name',
caption: 'caption',
description: 'description'
// display: 'popup'
},
callback
);
return false;
});
});</script>
<!-- Tweet code-->
Tweet
<!-- Facebook share code-->
<p id="msg">Share on Facebook</p>
</center>
</html>
"Domains, protocols and ports must match."
Typical mismatch in (older versions of ?) Safari is http://www.example.com and http://example.com.

Javascript File References Problem (with jQuery)

Before, I had this:
<head>
<script src="/Scripts/jquery-1.3.2.min.js" type="text/javascript"></script>
<script type="text/javascript">
var optPrompt = "- Select One -";
var subCats;
var parentCats;
var nextBtn;
var ParentChanged = function() {
ClearDescription();
if (this.selectedIndex == 0) {
$(subCats).html($("<option>").text(optPrompt));
}
$.getJSON('<%=Url.Action("GetChildCategories") %>', { parentId: $(this).val() },
function(data) {
subCats.options.length = 0;
$("<option>").text(optPrompt).appendTo(subCats);
$(data).each(function() {
$("<option>").attr("value", this.ID).text(this.Name).appendTo(subCats);
});
});
}
var DisplayDescription = function(catId) {
$.ajax({
url: '<%=Url.Action("GetDescription") %>',
data: { categoryId: catId },
dataType: 'html',
success: function(data) {
$("p#categoryDescription").html(data);
}
});
}
var ChildChanged = function() {
var catSelected = this.selectedIndex != 0;
if (!catSelected) ClearDescription();
else DisplayDescription($(this).val());
}
var ClearDescription = function() {
$("p#categoryDescription").html('');
}
$(function() {
parentCats = $("select#Category").get(0);
subCats = $("select#Subcategory").get(0);
nextBtn = $("input#nextButton").get(0);
$(parentCats).change(ParentChanged);
$(subCats).change(ChildChanged);
});
</script>
</head>
Then I put all of my inline script into a file (myScript.js) and changed my HTML to this:
<head>
<script src="/Scripts/jquery-1.3.2.min.js" type="text/javascript"></script>
<script src="/Scripts/myScript.js" type="text/javascript"></script>
</head>
And now nothing is working. I opened up my page in IE7 and it had a page error that read:
Line: 54
Error: Unknown name.
Line 54 happens to be the last line of my external javascript file.
What am I doing wrong?
Am I right in saying that this is ASP.Net? If it is, inline scripts like:
<%=Url.Action("GetDescription") %>
cannot go in the external JavaScript file.
Did you put the < script > tag inside your myScript.js? If yes, remove them.
Your myScript.js should start with
var optPrompt = "- Select One -";
Since you are now serving the js as a static file, rather than via your ASP, lines like
<%=Url.Action("GetChildCategories") %>
will no longer work as the server doesn't interpret them and replace them with the correct values. You'll need to hard-code them in the script, or leave those lines as inline scripts in the main page and set them as global variables which you can then reference from the external file.

Categories