What is the right syntax for injecting Javascript with PhantomJS? - javascript

My goal is to inject:
javascript document.getElementById("pickupZip").value = "90049";
document.getElementById("refreshStoresForZipPop").click();
into a website with PhantomJS. This is all of the code on my inject.js file, and I get this in the console: SyntaxError: Expected an identifier but found "document" instead, so I know it is the wrong syntax, though I can't find a place that shows what the correct is. Here is my code for the PhantomJS file:
var webPage = require('webpage');
var page = webPage.create();
page.open('http://shop.advanceautoparts.com/p/purolator-classic-air-filter-a24278/5792304-P?navigationPath=L1*14934/', function(status) {
var success = phantom.injectJs('inject.js');
console.log(success);
if (status === "success") {
page.includeJs('http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js', function() {
page.render('advanceautoparts.png');
phantom.exit();
});
}
});

Use evaluate.
var webPage = require('webpage');
var page = webPage.create();
page.open('http://shop.advanceautoparts.com/p/purolator-classic-air-filter-a24278/5792304-P?navigationPath=L1*14934/', function(status) {
var success = phantom.injectJs('inject.js');
console.log(success);
if (status === "success") {
page.includeJs('http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js', function() {
page.evaluate(function(s) {
document.getElementById("pickupZip").value = "90049";
document.getElementById("refreshStoresForZipPop").click();
});
page.render('advanceautoparts.png');
phantom.exit();
});
}
});
Reference: http://phantomjs.org/api/webpage/method/evaluate.html

Related

Parsing the Page

I wrote a small js script, I want to enter the site by login and password and parsing data birthday and name users on the page I need. But i do not know what i need to do further
var page = require('webpage').create();
phantom.cookiesEnabled = true;
page.open("http://www.facebook.com/login.php", function(status) {
if (status === "success") {
page.evaluate(function() {
document.getElementById("email").value = "login#mail.com";
document.getElementById("pass").value = "12345";
document.getElementById("u_0_1").click();
});
window.setTimeout(function() {
page.render("fb.png");
}, 5000);
page.open('https://www.facebook.com/friends/requests/?fcref=ff', function() {
window.setTimeout(function() {
page.render("fb2.png");
phantom.exit();
}, 5000);
});
}
});

TrifleJS quitting; "Unexpected ."

Can somebody tell me what is wrong with my syntax? While running this code in trifle JS it tells me that
. is unexpected at (2,4).
var page = require('webpage').create(),
page.open("http://www.phantomjs.org", function(status) {
if ( status === "success" ) {
page.includeJs("http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js", function() {
console.log(page.evaluate(function() {
return $("#intro").text();
}));
phantom.exit();
});
}
});
The problem is the ; at the end of the first line. This assumes that you define a variable in the next line which you don't do anymore. Exchange it with a semicolon:
var page = require('webpage').create();
page.open("http://www.phantomjs.org", function(status) {
//...
});

How to check if page is published

to check if page is published using server side code i should use this snippet:
PublishingPageCollection pages = PublishingWeb.GetPublishingWeb(web).GetPublishingPages();
foreach (PublishingPage page in pages)
{
if(!page.ListItem.File.Level == SPFileLevel.Published)
return;
// logic
}
How could i do the same but using Javascript in SharePoint?
According to SP.Publishing.PublishingWeb Methods the method GetPublishingPages is not supported in JSOM API.
But you could consider the following example to determine whether page is published or not using JSOM API
function getPublishingPages(success,error)
{
var ctx = SP.ClientContext.get_current();
var list = ctx.get_web().get_lists().getByTitle('Pages');
var items = list.getItems(SP.CamlQuery.createAllItemsQuery());
ctx.load(items,'Include(File)');
ctx.executeQueryAsync(function() {
success(items);
},
error);
}
SP.SOD.executeFunc('SP.js', 'SP.ClientContext', function() {
getPublishingPages(printPagesInfo,logError);
});
function printPagesInfo(pages)
{
pages.get_data().forEach(function(item){
var file = item.get_file();
var pageStatus = file.get_level() === SP.FileLevel.published ? 'published' : 'not published';
console.log(String.format('Page {0} is {1}', file.get_name(),pageStatus));
});
}
function logError(sender,args){
console.log('An error occured: ' + args.get_message());
}

asynchronous HTTP (ajax) request works in script tag but not in js file

I have this ajax call here in a script tag at the bottom of my page. Everything works fine! I can set a breakpoint inside the 'updatestatus' action method in my controller. My server gets posted too and the method gets called great! But when I put the javascript inside a js file the ajax call doesn't hit my server. All other code inside runs though, just not the ajax post call to the studentcontroller updatestatus method.
<script>
$(document).ready(function () {
console.log("ready!");
alert("entered student profile page");
});
var statusdropdown = document.getElementById("enumstatus");
statusdropdown.addEventListener("change", function (event) {
var id = "#Model.StudentId";
var url = '#Url.Action("UpdateStatus", "Student")';
var status = $(this).val();
$.post(url, { ID: id, Status: status }, function (data) {
// do something with the returned value e.g. display a message?
// for example - if(data) { // OK } else { // Oops }
});
var e = document.getElementById("enumstatus");
if (e.selectedIndex == 0) {
document.getElementById("statusbubble").style.backgroundColor = "#3fb34f";
} else {
document.getElementById("statusbubble").style.backgroundColor = "#b23f42";
}
}, false);
</script>
Now I put this at the bottom of my page now.
#section Scripts {
#Scripts.Render("~/bundles/studentprofile")
}
and inside my bundle.config file it looks like this
bundles.Add(new ScriptBundle("~/bundles/studentprofile").Include(
"~/Scripts/submitstatus.js"));
and submitstatus.js looks like this. I know it enters and runs this code because it I see the alert message and the background color changes. So the code is running. Its just not posting back to my server.
$(document).ready(function () {
console.log("ready!");
alert("submit status entered");
var statusdropdown = document.getElementById('enumstatus');
statusdropdown.addEventListener("change", function (event) {
var id = "#Model.StudentId";
var url = '#Url.Action("UpdateStatus", "Student")';
var status = $(this).val();
$.post(url, { ID: id, Status: status }, function (data) {
// do something with the returned value e.g. display a message?
// for example - if(data) { // OK } else { // Oops }
});
var e = document.getElementById('enumstatus');
if (e.selectedIndex == 0) {
document.getElementById("statusbubble").style.backgroundColor = "#3fb34f";
} else {
document.getElementById("statusbubble").style.backgroundColor = "#b23f42";
}
}, false);
});
In the console window I'm getting this error message.
POST https://localhost:44301/Student/#Url.Action(%22UpdateStatus%22,%20%22Student%22) 404 (Not Found)
Razor code is not parsed in external files so using var id = "#Model.StudentId"; in the main view will result in (say) var id = 236;, in the external script file it will result in var id = '#Model.StudentId'; (the value is not parsed)
You can either declare the variables in the main view
var id = "#Model.StudentId";
var url = '#Url.Action("UpdateStatus", "Student")';
and the external file will be able to access the values (remove the above 2 lines fro the external script file), or add them as data- attributes of the element, for example (I'm assuming enumstatus is a dropdownlist?)
#Html.DropDownListFor(m => m.enumStatus, yourSelectList, "Please select", new { data_id = Model.StudentId, data_url = Url.Action("UpdateStatus", "Student") })
which will render something like
<select id="enumStatus" name="enumStatus" data-id="236" data-url="/Student/UpdateStatus">
Then in the external file script you can access the values
var statusbubble = $('#statusbubble'); // cache this element
$('#enumStatus').change(function() {
var id = $(this).data('id');
var url = $(this).data('url');
var status = $(this).val();
$.post(url, { ID: id, Status: status }, function (data) {
....
});
// suggest you add/remove class names instead, but if you want inline styles then
if (status == someValue) { // the value of the first option?
statusbubble.css('backgroundColor', '#3fb34f');
} else {
statusbubble.css('backgroundColor', '#b23f42');
};
});

phantomjs + jquery: returns empty string

This webpage (test.html):
<p id="test">bla</p>
And this js code:
var page = require('webpage').create();
page.onConsoleMessage = function(msg) {
console.log("Message: "+msg);
};
page.open("http://localhost/test.html", function(status) {
if ( status === "success" ) {
page.includeJs("http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js", function() {
page.evaluate(function() {
console.log($("#test").text());
});
phantom.exit();
});
}
});
Result:
Message:
Does anybody know Why it doesn't display the text content of p when I run it with phantomjs?
try to use this one:
console.log($("#test").val());

Categories