protractor : passing variable 'url Json file' in executeAsyncScript - javascript

I'm new in protractor and I hope to have help regarding how to pass a variable in the executeAsyncScript function used in protractor tests.
I'm testing an application and i need to have a JSON file that contain the labels translation (French and English), at first I could correctly recuperate the language of the user from a first json file(let call getUser.json). Second on depending of the userlanguage I need to pass dynamically the url to get the labels json file (let call lang_fr.json and lang_en.json):
based on the code, 3rd exemple I could access to any json file.
browser.executeAsyncScript(function() {
var callback = arguments[arguments.length - 1];
var xhr = new XMLHttpRequest();
var url='path_to/getUser';
xhr.open("GET", url , true);
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200) {
callback(xhr.responseText);
}
};
xhr.send('');
}).then(function(str) {
browser.params.lang=JSON.parse(str)['userLanguage'];
if(JSON.parse(str)['userLanguage']==='fr')
browser.params.url='path_to/lang_en.json';
else
browser.params.url='path_to/lang_fr.json';
UserLanguage.UserLanguage(); /// excuting the fct that call the second jsonfile
now I need to pass the browser.params.urlexecuteAsyncScript to get the json file labels So i do this in another export file:
var url = browser.params.url;
browser.logger.info(browser.params.url); // The url depending the user language is correctly displayed
browser.executeAsyncScript(function() {
var callback = arguments[arguments.length - 1];
var xhr = new XMLHttpRequest();
xhr.open('GET', url /*here to pass the url depending the user language*/, true);
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
callback(xhr.responseText);
}
}
xhr.send()
}, url/*passed on second argument*/).then(function(jsonlabel) {
/// rest of the code to resolve the labels
I got that the url is not defined
I checked the following examples:
Executing Async Javascript in Protractor http://blog.ng-book.com/executing-async-javascript-in-protractor/
But in every example I got errors.
So could you please provide me with your suggestion how can I pass correctly the vaiable url in the script? note that when I put the absolute file path it work:
xhr.open('GET', 'path_to/lang_en.json', true);
But I need to pass it dynamically. Hope it's clear and I am here for further details.

So I tried to put the variable url on function(){ and it works!
{
var url = browser.params.url;
var languageUser = browser.params.lang
browser.logger.info(browser.params.url); // The url depending the user language is correctly displayed
browser.executeAsyncScript(function(url /// added here){
var callback = arguments[arguments.length - 1];
var xhr = new XMLHttpRequest();
xhr.open('GET', url, true); xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200) {
callback(xhr.responseText);
}
}
xhr.send()
}, url).then(function(resJson) {//rest of the code

Related

How to grab a specific part of a returned GET in javascript?

I am trying to return a webpage, and grab the part of the page labeled: Description. I want to be able to split the returned HTML, but with the "" that are in HTML it will not work correctly.
This is for a template to allow a user on an extension to be able to add a pre-loaded string to fill in a box. I have tried splitting the string at a set word, but my knowledge does not extend past trying to use the string.
function pullWebpage(){
var data = null;
var xhr = new XMLHttpRequest();
xhr.withCredentials = true;
xhr.addEventListener("readystatechange", function () {
if (this.readyState === 4) {
var response = this.responseText;
response.split("Description");
console.log(response);
}
});
xhr.open("GET", "https://jira2.cerner.com/browse/ION-25843?", true);
xhr.setRequestHeader("Cache-Control", "no-cache");
xhr.setRequestHeader("cache-control", "no-cache");
xhr.send(data);
}
I want to be able to successfully pull out the description of the page pulled in the GET, and use this to set up an automatic template. HTML returned in GET using postman here
While the issue before was based on grabbing the whole HTML, using the rest api was a better solution. Changing the code to:
var data = null;
var xhr = new XMLHttpRequest();
xhr.withCredentials = true;
xhr.addEventListener("readystatechange", function () {
if (this.readyState === 4) {
var response = JSON.parse(this.responseText);
console.log(response.fields.description);
}
});
xhr.open("GET", "https://jira2.cerner.com/rest/api/2/issue/ION-25843");
xhr.setRequestHeader("Content-Type", "application/json");
xhr.send(data);
Allows for the code to go out and grab the json of the page, and then grab the specific definition of the page.

How to retrieve a html file content and insert to another html file?

I am trying to write templates for a mobile app, as I only know pure JavaScript, so my plan is replacing the default template with a new one. After few hours I was nearly exhausted on this issue. It is not CORS thing and all the files are in localhost.
function getTheme(){
var xhr = new XMLHttpRequest();
xhr.open("GET", "model/1/index.html", true);
xhr.responseType = "document";
xhr.onreadystatechange = function() {
if (xhr.readyState === 4) {
if (xhr.status === 0) {
var customTheme = document.getElementById('crapDiv');
customTheme.innerHTML = xhr.responseXML;
}
}
}
xhr.send(null);
}
This Ajax works quite fine when I test with a text file, but as MDN said, to retrieve a html with ajax, a "document" responseType must be declared, thus, with the xhr.responseXML it only returns a DOM object, which is [object HTMLDocument]
I just can not parse this object back into contents so that I could not insert it into another html file.
So, How could I get through with this issue plz? and, plz only pure JS code.
You can't edit a file's content with JavaScripts, you can only read it. It's not for that. You need a server with eg PHP that can save your data.
You can get the response data as raw text with xhr.responseText.
Finally I got it.
function getTheme(){
var xhr = new XMLHttpRequest();
xhr.open("GET", "model/1/index.html", true);
xhr.onreadystatechange = function() {
if (xhr.readyState === 4) {
if (xhr.status === 0) {
var customTheme = document.getElementById('crapDiv');
customTheme.innerHTML = xhr.responseText;
}
}
}
xhr.send(null);
}
The diff is just the declare of the responseType, by default it is "", and xhr.responseText is the right way to retrieve the content, while the xhr.responseXML is the right way to retrieve the DOM object.
As it should be xhr.responseText, so there is no more need to declare responseType, and must be "" or "Text" if you still want a decalration.
Thnx.

Wpf webbrowser load html with javascript

I have this function in my JavaScript function:
var xhr = new XMLHttpRequest();
var url = 'url';
xhr.open('GET', url, false);
xhr.onreadystatechange = function () {
if (xhr.readyState == 4) {
var str = xhr.responseText;
alert(str);
var resp = JSON.parse(str);
alert('12');
if (0 == resp.ErrorCode) {
alert('13');
}
}
}
xhr.send();
The str is always :
{"ErrorCode":0,"ErrorMessage":"OK","Command":"/api/getvideoinfo/","data":[{"VideoID":"ehcVomMexkY","IsInCache":true,"IsDownloading":false,"AvailableFormats":[{"DisplayName":"720","IsHD":true,"VidEncMimeType":"video/H264","AudEndMimeType":"audio/aac","Width":1280,"Height":720,"PlaybackURL":"","IsDefaultStream":false},{"DisplayName":"360","IsHD":false,"VidEncMimeType":"video/H264","AudEndMimeType":"audio/aac","Width":640,"Height":360,"PlaybackURL":"url","IsDefaultStream":true}]}]}
And i noticed that the script never get to :
alert('12');
Any idea what can cause this?Why the json won't parse? did i need to add any library to the html?
The url is the location of the file on the server. So the url variable should be the path from where you get the data which in this case should be
var url = "/api/getvideoinfo/";

Write line to text file with AJAX XMLHttpRequest

Here is my javascript function that reads from the file every second and outputs it:
var timer;
var url = "http://.../testdata.txt";
function ajaxcall() {
var lines;
var alltext;
request = new XMLHttpRequest();
request.open("GET", url, true);
request.onreadystatechange = function() {
if (request.readyState === 4) { // document is ready to parse.
if (request.status === 200) { // file is found
allText = request.responseText;
lines = request.responseText.split("\n");
document.getElementById("test").innerHTML = "";
for (i in lines) {
document.getElementById("test").innerHTML += lines[i] + "<br>";
}
}
}
}
request.send();
}
timer = setInterval(ajaxcall, 1000);
I haven't got the hang of AJAX yet so I tried to make a similar way to write into the file using what I read on the internet:
function chat() {
request = new XMLHttpRequest();
request.open("POST", url, true);
request.send("\n" + document.getElementById("chatbox").value);
}
However that does absolutely nothing and I don't understand why. The element "chatbox" is input type textbox and chat() is called by input type submit.
You cannot write to a file using just a POST call. In fact, you cant write to a file using only JavaScript/AJAX. You will need a server-side script in for example PHP that will write to the file for you, and then you need to call this script using AJAX.

Reading first line of a text file in javascript

Let's say I have a text file on my web server under /today/changelog-en.txt which stores information about updates to my website. Each section starts with a version number, then a list of the changes.
Because of this, the first line of the file always contains the latest version number, which I'd like to read out using plain JavaScript (no jQuery). Is this possible, and if yes, how?
This should be simple enough using XHR. Something like this would work fine for you:
var XHR = new XMLHttpRequest();
XHR.open("GET", "/today/changelog-en.txt", true);
XHR.send();
XHR.onload = function (){
console.log( XHR.responseText.slice(0, XHR.responseText.indexOf("\n")) );
};
So seeing as the txt file is externally available ie: corresponds to a URL, we can do an XHR/AJAX request to get the data. Note without jQuery, so we'll be writing slightly more verbose vanilla JavaScript.
var xmlHttp;
function GetData( url, callback ) {
xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = callback;
xmlHttp.open( "GET", url, true );
xmlHttp.send( null );
}
GetData( "/today/changelog-en.txt" , function() {
if ( xmlHttp.readyState == 4 && xmlHttp.status == 200 {
var result = xmlHttp.responseText;
var allLines = result.split("\n");
// do what you want with the result
// ie: split lines and show the first line
var lineOne = allLines[0];
} else {
// handle the error
}
});

Categories