Open URL from file system using PhantomJS - phantomjs

In page.open I can read about how to open a page using http.
How do use the WebPage module to open an url from the file system?
I have tried to omit http:// and have an url with ../some_dir/foo.html, but it seems to fail.
I Have tried this:
var page = require('webpage').create();
var fs = require('fs');
fs.changeWorkingDirectory('../foo/bar');
page.open('file://index.html', function(status)
{
console.log(status);
//console.log(document.title);
phantom.exit();
});
which outputs "fail".
I got the advice to test an absolute path, trying this:
var page = require('webpage').create();
var fs = require('fs');
page.open('file:///absolute/path/to/index.html', function(status)
{
console.log(page.title);
console.log($('body').length);
phantom.exit();
});
(with and without the call to changeWorkingDirectory, but with the same result)
I get a page title, but phantomjs reports that $ is undefined, jQuery is included in my html file (that is too large to post here). It is included like this:
<script type="text/javascript" src="js/jquery-1.11.1.min.js"></script>
Trying to run functions also produces errors like
Can´t find variable: function_name

Does the page/file you are opening already have jquery embedded on the page? If not, you will need to use either injectJs or includeJs on the page object before you can use the $ operator.
http://phantomjs.org/page-automation.html
If you are just doing a simple DOM selection, I would recommend just calling
document.querySelector('body').length
As these functions already exist within the Phantom instance.

Related

JSReport External javascript with Json data required

We have hosted jsreport node application on EBS. We created template and using css and javascripts from a static website(hosted internally). In the external javascript file we are using variables similar to what jsreport requires i.e. {{variablename}} which does not work. When we add the javascript inline in the template it works.
We know there should be some other way around to specify this but could not find it.
This won't work. jsreport templating engines only compile and process the html output, not the referenced scripts.
However you can try this approach:
Put a placeholder in a template content where you want to put external script. Lets say we want to put inline jquery
<script>
$$$myScript
</script>
<script>
$(() => {
alert('yes I have jquery inlined')
})
</script>
Create jsreport custom server script which downloads your external script, in this case jquery, and replace the placeholder with its content
var getReq = require('request').get
function beforeRender(req, res, done) {
getReq('https://code.jquery.com/jquery-3.1.0.min.js', (err, res, body) => {
req.template.content = req.template.content.replace('$$$myScript', body.toString())
done()
})
}
The script will run before the templating engines are executed therefore you can use templating engines tags inside it now.
playground live demo here

Casperjs cannot access same global objects as in from browsers console

I am new to Casperjs, phantomjs .I have been trying hard to create some page automation to login and take some steps in a CMS but i am having issues with accessing the global window variables from casperjs evaluate() function. the below example is just checking jquery on Google. Jquery exists in the page and some other global functions but i can't access them from casperjs.
casper.start('https://www.google.ca/#hl=en', function() {
// search for 'casperjs' from google form
this.fill('form[action="/search"]', { q: 'casperjs' }, false);
});
casper.then(function() {
this.evaluate(function jquery() {
console.log('looking for jquery ---');
console.log($ + 'exists');
});
});
getting error - `ReferenceError: Can't find variable: $
How can i fix this ?
Any help is appreciated :)
For use jQuery in casperjs
inject script in page, something like:
var casper = require('casper').create({
some code here,
clientScripts: ['/path/to/jquery.js'],
});

reCAPTCHA not showing after page refresh

Why is google reCaptcha2 (gReCaptcha) not showing after a page refresh, but showing if page is reopened by the link?
See this video for explanation: http://take.ms/I2a9Z
Page url: https://orlov.io/signup
Page first open: captcha exists.
Navigate by link: captcha exists.
Open new browser tab: captcha exists.
Refreshing page by refresh icon, ctrl+R, ctrl+F5: captcha NOT exists.
I added body unload event to prevent browser cache, it did not help.
Browsers for testing:
Firefix 39.0
Chome: 44.0.2403.125 m
Opera: 30.0
In all browsers I get the same result. So does this mean there's an error on my side?
I think it has to do with the browser and the speed of your network. You are calling ReCaptcha with a callback, but you call it before you define the callback. Depending on your network speed or browser quirks, it might execute before the rest of the script has loaded.
Line 330:
<script src="//www.google.com/recaptcha/api.js?onload=renderReCaptchaCallback&render=explicit&hl=en-US" async defer></script>
Line 351:
<script type="text/javascript">if (typeof (renderReCaptchaCallback) === "undefined") {
var reCaptchaWidgets = {};
var renderReCaptchaCallback = function() {
jQuery.each(reCaptchaWidgets, function(widgetId, widgetOptions) {
grecaptcha.render(document.getElementById(widgetId), widgetOptions);
});
};
}</script>
So I would move the definition of renderReCaptchaCallback to the top of the page so it is defined well before trying to load it.

ExtJS4 - How to make an initial entry to a site with param data?

I have an ExtJS4 site www.mysite.com where I serve index.html when a user enter the site. I want the user to be able to access the site with some param data redirected from another site. For example, www.mysite.com?q=10
How do I capture q=10 which I will use to retrieve some data from the database?
How do I send index.html so that browser retrieves javascript and css files. Once all the javascript and css files are loaded, I need to render a page displaying the result from the database?
Thanks
To get the url parameters I've done this :
var getParams = document.URL.split("?");
var params = Ext.urlDecode(getParams[getParams.length - 1]);
console.log(params.q) // you should see 10 being printed
If index.html is gonna come with some param in the url you can use the launch method to do an ajax request and bassed on that response render something
Ext.application({
name : 'MyAppWithDynamicFirstPage',
launch : function() {
var getParams = document.URL.split("?");
var params = Ext.urlDecode(getParams[getParams.length - 1]);
var q = params.q;
Ext.Ajax.request({
url: 'someServlet/getViewToRender',
params: {
'q': q
},
success: function(response, opts) {
//bassed on this you would do something else like render some specific panel on your viewport
},
failure: function(response, opts) {
console.log('server-side failure with status code ' + response.status);
}
});
}
});
I hope this was of some help.
Best regards.
Depends of your web server, programming language and architecture
Usually first ExtJs is loading with all js/css. After it loaded, data loads asynchronously from the server. But if you exactly know what are you doing, you can render your data into a global variable inside a script tag and then use it in the code.

Loading audio via a Blob URL fails in Safari

Following code works in Chrome (22.0) but not in Safari (6.0)
<!DOCTYPE html>
<html>
<head>
<script>
function onGo(e) {
var fr = new FileReader();
var file = document.getElementById("file").files[0];
fr.onload = function(e) {
var data = new Uint8Array(e.target.result);
var blob = new Blob([data], {type: 'audio/mpeg'});
var audio = document.createElement('audio');
audio.addEventListener('loadeddata', function(e) {
audio.play();
}, false);
audio.addEventListener('error', function(e) {
console.log('error!', e);
}, false);
audio.src = webkitURL.createObjectURL(blob);
};
fr.readAsArrayBuffer(file);
}
</script>
</head>
<body>
<input type="file" id="file" name="file" />
<input type="submit" id="go" onclick="onGo()" value="Go" />
</body>
</html>
In Safari, neither callback (loadeddata nor error) is called.
The content used is an mp3 file, which is normally played back with audio tag.
Is there any special care needed for Safari?
Many years later, I believe the example in the OP should work just fine. As long as you somehow set the mime type when creating the blob, like the OP does above with the type property of the options passed in:
new Blob([data], {type: 'audio/mpeg'});
You could also use a <source> element inside of an audio element and set the type attribute of the <source> element. I have an example of this here:
https://lastmjs.github.io/safari-object-url-test
And here is the code:
const response = await window.fetch('https://upload.wikimedia.org/wikipedia/commons/transcoded/a/ab/Alexander_Graham_Bell%27s_Voice.ogg/Alexander_Graham_Bell%27s_Voice.ogg.mp3');
const audioArrayBuffer = await response.arrayBuffer();
const audioBlob = new Blob([audioArrayBuffer]);
const audioObjectURL = window.URL.createObjectURL(audioBlob);
const audioElement = document.createElement('audio');
audioElement.setAttribute('controls', true);
document.body.appendChild(audioElement);
const sourceElement = document.createElement('source');
audioElement.appendChild(sourceElement);
sourceElement.src = audioObjectURL;
sourceElement.type = 'audio/mp3';
I prefer just setting the mime type of the blob when creating it. The <source> element src attribute/property cannot be updated dynamically.
I have the same problem, and I spend a couple days troubleshooting this already.
As pwray mentioned in this other post, Safari requires file extensions for media requests:
HTML5 Audio files fail to load in Safari
I tried to save my blob to a file, named it file.mp3 and Safari was able to load the audio that way, but after I renamed the file to have no extension (just "file"), it didn't load.
When I tried the url created from the blob in another tab in Safari:
url = webkitURL.createObjectURL(blob);
it download a file right away called "unknown", but when I tried the same thing in Chrome (also on Mac), it showed the content of the file in the browser (mp3 files start with ID3, then a bunch of non-readable characters).
I couldn't figure out yet how I could force the url made of blob to have an extension, because usually it looks like this:
blob:https://example.com/a7e38943-559c-43ea-b6dd-6820b70ca1e2
so the end of it looks like a session variable.
This is where I got stuck and I would really like to see a solution from some smart people here.
Thanks,
Steven
Sometimes, HTML5 audio can just stop loading without any apparent reason.
If you take a look to the Media Events (http://www.w3schools.com/tags/ref_eventattributes.asp) you´ll see an event called: "onStalled", the definition is "Script to be run when the browser is unable to fetch the media data for whatever reason" and it seems that it should be helpful for you.
Try listening for that event and reloading the file if necessary, with something like this:
audio.addEventListener('onstalled', function(e) {
audio.load();
}, false);
I hope it helps!
Just use source tag in audio.
<audio controls>
<source src="blob" type="blobType">
</audio>