I am creating a new element and trying to get the response back which should be a url but I am not sure how to get the response back from the new element. Any suggestions would be great.
public void Setup()
{
IJavaScriptExecutor js = (IJavaScriptExecutor)driver;
driver = new ChromeDriver("C:\\SeleniumDrivers\\");
driver.Navigate().GoToUrl("https://www.target.com");
driver.Manage().Window.Maximize();
Thread.Sleep(3000);
string execu = "var document = window.document;"+
"var head = window.getElementByTagName(\"head\");"+
"var script = window.createElement(\"script\");" +
"script.setAttribute(\"type\", \"text/javascript\");" +
"script.setAttribute(\"src\", \"https://go.playerzero.ai/record/6274691b00fbad01561df689\");"+
"head.appendChild(script);";
try
{
js.ExecuteScript(execu);
}
catch (Exception e)
{
System.Diagnostics.Debug.WriteLine(e);
}
}
Modify your script to return the src:
This is a working example using .NET6, Selenium.WebDriver 4.3.0, Selenium.WebDriver.ChromeDriver 103.0.5060.5300
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
const string Url = #"https://www.target.com";
using var driver = new ChromeDriver();
driver.Navigate().GoToUrl(Url);
var script = #"let script = document.createElement('script');
script.type = 'text/javascript';
script.src = 'https://go.playerzero.ai/record/6274691b00fbad01561df689';
document.head.appendChild(script);
return script.src;";
var js = (IJavaScriptExecutor)driver;
var src = js.ExecuteScript(script).ToString();
Console.WriteLine(src);
Related
I have a page that allows a user to click a button, and it makes a WebAPI call to my .Net backend controller which generates a PDFSharp document object. I need to return that (binary?) object to the Knockout/Javascript caller on the UI, and present a Save As dialog... or else just start downloading it automatically.
This is my attempt, but it's not right.
[System.Web.Http.Route("GeneratePdf"), System.Web.Http.HttpPost]
public HttpResponseMessage GeneratePdf(PlateTemplateExtendedDto data)
{
var doc = GeneratePdf(new PlateService().CreateTemplate(true), "my.pdf");
HttpResponseMessage result = null;
var pdfContent = new MemoryStream();
doc.Save(pdfContent);
result = Request.CreateResponse(HttpStatusCode.OK);
result.Content = new StreamContent(new FileStream(pdfContent, FileMode.Open, FileAccess.Read));
result.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment");
result.Content.Headers.ContentDisposition.FileName = "SampleImg"
//pdfContent.Position = 0;
var res = new HttpResponseMessage();
res.Content = new ByteArrayContent(pdfContent.ToArray());
HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);
res.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment");
res.Content.Headers.ContentDisposition.FileName = data.Description;
res.Content.Headers.ContentType = new MediaTypeHeaderValue("application/pdf");
return res;
}
Firstly, the line:
new StreamContent(new FileStream(pdfContent, FileMode.Open, FileAccess.Read));
is invalid. 'pdfContent' should be a string, I think.
Secondly, I'm not sure how to handle a 'HttpResponseMessage' on the front end. How do I turn that into a Download?
Web api may be something like this..
[System.Web.Http.Route("GeneratePdf"), System.Web.Http.HttpGet]
public IHttpActionResult GeneratePdf(PlateTemplateExtendedDto data)
{
var doc = GeneratePdf(new PlateService().CreateTemplate(true), "my.pdf");
var pdfContent = new MemoryStream();
doc.Save(pdfContent);
var content = new StreamContent(pdfContent);
content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment");
content.Headers.ContentDisposition.FileName = data.Description;
content.Headers.ContentType = new MediaTypeHeaderValue("application/pdf");
content.Headers.ContentLength = pdfContent.GetBuffer().Length;
return Ok(content);
}
you only set api url with PlateTemplateExtendedDto parameters to window.location on client side
I have a server side script that dynamically creates a js file in an s3 bucket after a given url has 1 page view. The server side script runs every 1 minute.
On any given URL on the site, I have a script which tries to call this dynamically created file.
Such as:
var host = window.location.host;
var pathName = window.location.pathname;
var script = document.createElement('script');
script.async = true;
script.type = 'text/javascript';
script.src="https://s3.amazonaws.com/some_bucket/"+host+pathName+".js;
var node = document.getElementsByTagName('script')[0];
node.parentNode.insertBefore(script, node);
})();
The problem is that if a new URL is created on the site and the first visitor goes to that page then the cron job has had a chance to run, and therefore the js file does not exist in the bucket yet. This causes a 404 error but also causes an error in the on-page javascript above crashing the js library that contains it.
Is there a way to check the existence of the file on the fly and default to a different file if the dynamically created one has not been built yet?
For example (pseudo code):
try{
script.src="https://s3.amazonaws.com/some_bucket/"+host+pathName+".js;
}
catch(e){
404error = true;
}
finally{
if(404error == true){
script.src="https://s3.amazonaws.com/some_bucket/DEFAULT.js";
}
}
Updated code with calling a different file on error. This successfully calls the other file, however it also still causes a 404 error in Chrome.
var host = window.location.host;
var pathName = window.location.pathname;
var script = document.createElement('script');
script.async = true;
script.type = 'text/javascript';
script.onerror = function(){
var host = window.location.host;
var pathName = window.location.pathname;
var script = document.createElement('script');
script.async = true;
script.type = 'text/javascript';
script.src="https://s3.amazonaws.com/some_bucket/some_default_file.js";
var node = document.getElementsByTagName('script')[0];
node.parentNode.insertBefore(script, node);
}
script.src="https://s3.amazonaws.com/some_bucket/"+host+pathName+".js;
var node = document.getElementsByTagName('script')[0];
node.parentNode.insertBefore(script, node);
})();
Use script.onerror:
var pathName = window.location.pathname;
var script = document.createElement('script');
script.async = true;
script.type = 'text/javascript';
script.onerror = function() {
console.log('script failed to load');
};
script.src = "https://s3.amazonaws.com/some_bucket/" + host + pathName + ".js";
var node = document.getElementsByTagName('script')[0];
node.parentNode.insertBefore(script, node);
This is my java script code for downloading the file from database on button click, when the button clicks this function calls. using ajax call i have moved to handler.
function DownloadDocument() {
var CurrentUserEmpId = CurrentSelectedUser;
Ext.Ajax.request({
url: "UploadAttachment.ashx?mode=DownloadDocument&EmployeeId=" + CurrentUserEmpId,
success: function (response) {
var data = response.responseText;
},
failure: function (form, action) {
}
});
}
Here comes the handler page, I have got bytes of my file to byte[] buffer. The problem here is download not working. I could't figure out the problem, since Iam a beginner. Please help with this, Thankyou.
case "DownloadDocument":
WebClient web = new WebClient();
try
{
byte[] buffer;
var query2 = #"select LLD_Decleration_doc from (select instance, Employee_id, lld_Decleration_doc, ROW_NUMBER() OVER(PARTITION BY Employee_id ORDER BY Update_Date DESC) Latest from [EManager].[dbo].[tax_benefit_declaration]) a where latest = 1 And Employee_id = #EmployeeId";
using (SqlConnection con = new SqlConnection(db.ConnectionString))
using (SqlCommand cmd = new SqlCommand(query2, con))
{
SqlParameter param = cmd.Parameters.Add("#EmployeeId", SqlDbType.Int);
param.Value = EmployeeId;
con.Open();
buffer = (byte[])cmd.ExecuteScalar();
con.Close();
}
HttpResponse response = HttpContext.Current.Response;
response.Clear();
response.ClearContent();
response.ClearHeaders();
response.Buffer = true;
response.ContentType = "APPLICATION/OCTET-STREAM";
String Header = "Attachment; Filename=NewFile";
response.AppendHeader("Content-Disposition", Header);
context.Response.BinaryWrite(buffer);
response.End();
}
catch { }
break;
}
This is something that it was said many times. You cant do this with Ajax call.
You can achive this by invoke hidden iframe for example:
var body = Ext.getBody();
var comp = body.getById('hiddenform-iframe-download');
if (!Ext.isEmpty(comp)) {
comp.remove();
}
body.createChild({
tag: 'iframe',
cls: 'x-hidden',
id: 'hiddenform-iframe-download',
name: 'iframe',
src: "yourContextToDownload?param1="+something
});
Im in the process of creating a custom timesheet using Google Docs and Google Apps Script. One of the requirements is to save the timsheet as a PDF when the user submits the timesheet. Heres what I currently have:
function createPdf(){
var ss = SpreadsheetApp.getActiveSpreadsheet();
var oauthConfig = UrlFetchApp.addOAuthService("google");
oauthConfig.setAccessTokenUrl("https://www.google.com/accounts/OAuthGetAccessToken");
oauthConfig.setRequestTokenUrl("https://www.google.com/accounts/OAuthGetRequestToken?scope=https://spreadsheets.google.com/feeds/");
oauthConfig.setAuthorizationUrl("https://www.google.com/accounts/OAuthAuthorizeToken");
oauthConfig.setConsumerKey("anonymous");
oauthConfig.setConsumerSecret("anonymous");
var url = "https://spreadsheets.google.com/feeds/download/spreadsheets/Export?key="
+ ss.getId() + "&gid=0&portrait=true" +"&exportFormat=pdf";
var requestData = {
"oAuthServiceName": "google",
"oAuthUseToken": "always"
};
var result = UrlFetchApp.fetch(url, requestData);
var content = result.getBlob();
var file = DocsList.createFile(content);
return file;
}
When debugging the script, I get the following error:
Unexpected exception upon serializing continuation
Any help would be appreciated.
After some further digging, I found this solution:
function createPdf(){
var ss = SpreadsheetApp.getActiveSpreadsheet();
var pdf = ss.getAs("application/pdf");
var file = DocsList.createFile(pdf);
file.rename("Test");
return file;
}
I have to load some script source dynamically. Since I can not use jQuery and did not know about the XmlHttpRequest+eval method, I tried to do it this way:
API.prototype.initCallback = null;
API.prototype.sourceLoadCnt = 0;
API.prototype.sourceReady = function () {
this.sourceLoadCnt--;
if(this.sourceLoadCnt===0){
this.initCallback(); //if all sources loaded
}
}
API.prototype.init = function (callback) {
this.initCallback = callback;
var _this = this;
var js = "../../js/";
var script1 = document.createElement('script');
script1.type = 'text/javascript';
script1.src = js+'script1.js';
this.sourceLoadCnt++;
script1.onload = function(){ _this.sourceReady() };
var script2 = document.createElement('script');
script2.type = 'text/javascript';
script2.src = js+'script2.js';
this.sourceLoadCnt++;
script2.onload = function(){ _this.sourceReady() };
var css1 = document.createElement('link');
css1.type = 'text/css';
css1.rel = 'stylesheet';
css1.href = 'style.css';
css1.media = 'screen';
this.sourceLoadCnt++;
css1.onload = function(){ _this.sourceReady() };
head.appendChild(script1);
head.appendChild(script2);
head.appendChild(css1);
};
My problem is, that the sourceReady-function is called only once.
I still could change everything to load it via XmlHttpRequest but I am curious why my way isn't working. Does anyone have an idea?
It might be because API.prototype.sourceLoadCnt should not exist, it should be an instance variable that lives on this.
The way you have coded it now will only work if you only have a single instance, and if you only have a single instance, going the oob/prototype way seems like a design failure.