save Iframe's source as an image on desktop - javascript

I have an Iframe in a webpage whose source is filled when a submit button is clicked.I need the iframe source to be saved as an image on my desktop .How can this be done.
Heres the code:
<iframe id="IFAEventPerformance" name="IFAEventPerformance" scrolling="auto" runat="server"
width="100%" height="403" class=""></iframe>
and the cs file:
protected void lnkBTNSubmit_Click(object sender, EventArgs e)
{
this.IFrame1.Attributes.Add("src", "https:\\anotherwebsitename");
}
function for export to ppt is:
protected void imgBTNExportPPT_Click(object sender, ImageClickEventArgs e)
{
//WebsiteToImage websiteToImage = new WebsiteToImage("http://www.google.co.in", #"C:\Users\312220\Desktop\myscreenshot.jpg");
//websiteToImage.Generate();
WebsiteToImage websiteToImage = new WebsiteToImage("C:\\Users\\304485\\Desktop\\Login.htm",(#"D:\\my\\chocos\\sample.jpg"));
websiteToImage.Generate();
TextBox txtTextBoxRetailGroup = (TextBox)uscRetailParameters.FindControl("txtRetailCustomerGroup");
TextBox txtTextBoxPPGroup = (TextBox)uscRetailParameters.FindControl("txtProductGroup");
TextBox txtTextBoxEventID = (TextBox)uscEventParameters.FindControl("txtEventId");
string RetailGrp;
RetailGrp = txtTextBoxRetailGroup.Text;
string PPGrp;
PPGrp = txtTextBoxPPGroup.Text;
string EventID;
EventID = txtTextBoxEventID.Text;
ShowPresentation();
GC.Collect();
}

Make an iframe available on your caller page. Load the ppt as the src/href for the frame.
If the users browser settings allow it, the ppt will be shown in the frame.
i believe this has nothing to do with .NET though

Related

How do I display an image saved within a file location in a new window by clicking a gridview link? A Terms Popup (modal) should display in between

Ok for a couple of weeks I have been stuck on a problem with one of my branches legacy applications.
I have a gridview and when I click on a link in the gridview I get a relevant image displayed within a new window. A new requirement has come in requesting that after clicking on the new window, the user should be displayed a "Terms of Use" pop up which they need to agree. After agreeing, the image should load in the new window as before.
I tried creating a popup with a modal.dialog using a bit of jquery and a div and I can get this to show. However any attempt I have made to open the image from this pop up has not worked. I think the index of the gridview gets lost when displaying the modal pop up.
The application is about 12 years old (waaaay before me). It was developed in c# and asp.net web forms.
I am new to stack. Apologies about formatting. The filestream code was in there for ages. Would there be a better way of doing this? Thank you for any help in advance.
So the user clicks on link within gridview -> A pop up displays the terms with an Agree button and ideally a cancel button too. User agrees and the popup displays image.
'''<%--button in gridview.--%>
<asp:LinkButton ID="btnOpenObject" runat="server" Text="View" OnClick="OpenObjectSelect_Click"
AlternateText="Opens Object in a new window" OnClientClick="aspnetForm.target= '_blank';" ToolTip="Opens in a new window"
CssClass="btnHyperLinkEnabled">
</asp:LinkButton>
'''<%--modal pop up.--%>
<div id="ModalMessage" title="testWindow" class="divAcceptWindow" style="display: none;">
<label style="font-weight: bold" class="boldCentral">Copying and Copyright Declaration</label>
<br />
This declaration has been issued under rule 5(3).
I declare that: blah blah…
<input type="button" id="okButton" value="I Agree" name="okButton" />
</div>
<script type="text/javascript">
//script to call popup
function showdialog() {
$("#ModalMessage").dialog({ modal: true });
$("#ModalMessage").dialog({ width: 500 });
$(".ui-dialog-titlebar").hide();
scrollTo(0, 0);
}
//script to show image from serverside
$('#okButton').click(function () {
$('#ModalMessage').dialog('close');
var dataToSend = { MethodName: 'IAgree' };
var options =
{
data: dataToSend,
dataType: 'JSON',
type: 'POST',
}
$.ajax(options);
});
</script>
'''//c# (code behind)
'''//Gridview link button click event
protected void OpenObjectSelect_Click(object sender, EventArgs e)
{
LinkButton b = (LinkButton)sender;
int miIndex = Convert.ToInt32(b.CommandArgument);
LocalSearch.DetailPosition = miIndex;
miArchiveItemId = LocalSearch.ArchiveItems[LocalSearch.DetailPosition].ArchiveItemId;
//call popup
this.Page.ClientScript.RegisterStartupScript(this.GetType(), "CallMyFunction", "showdialog()", true);
}
protected void Page_Load(object sender, System.EventArgs e)
{
//hook of jquery button click with method. This is hit after clicking I agree on pop up.
if (!Page.IsPostBack) {
if (Request.Form["MethodName"] == "IAgree") // same Method Name that we are specifying on client side
{
Agree();
return;
}
}
}
'''// Get information relating to image to pass to file stream
private void Agree()
{
ArchiveItem myArchiveItem = new ArchiveItem();
miArchiveItemId = Trunks;
if (miArchiveItemId > 0)
{
//Retrieve data from DB.
myArchiveItem = mysearchMediator.GetArchiveItemByID(miArchiveItemId);
}
DigitalObjectLink(myArchiveItem);
}
//Display the image using a file stream.
//Code works to display image without the file modal
public void DigitalObjectLink(ArchiveItem myArchiveItem)
{
LinkButton OpenObject = new LinkButton();
for (int i = 0; i < GridView1.Rows.Count; i++)
{
OpenObject = (LinkButton)GridView1.Rows[0].FindControl("btnOpenObject");
OpenObject.OnClientClick = "aspnetForm.target ='_blank';";
}
try
{
string path = ConfigurationManager.AppSettings["ImageFilePath"] + '\\' + myArchiveItem.RelativeFolderPath +
'\\' + myArchiveItem.FileName;
//string path = "C:" + '\\' + "Temp" + '\\' + myArchiveItem.FileName;
FileStream fs = File.Open(path, FileMode.Open, FileAccess.Read, FileShare.Read);
byte[] ar = new byte[(int)fs.Length];
Response.AddHeader("content-disposition", "attachment;filename=" + myArchiveItem.FileName);
Response.ContentType = "application/octectstream";
ClientScript.RegisterStartupScript(GetType(), "Javascript", "javascript:showdialog('" + path + "'); ", true);
fs.Read(ar, 0, (int)fs.Length);
fs.Close();
Response.BinaryWrite(ar);
Response.Flush();
Response.End();
}
catch
{
/*
** Hide Navigation & GridView & Show File Not Found Panel
*/
OpenObject.OnClientClick = "aspnetForm.target ='_self';";
this.NavigationControl1.Visible = false;
this.NavigationControl2.Visible = false;
this.GridView1.Visible = false;
lblFileNotFound.CssClass = "SearchResultsCount";
btnContactUs.Text = "Please contact PRONI quoting reference: " + myArchiveItem.Reference;
}
}

Dynamic web scraping with C#

I am trying to scrape the web page with C# and I am using HtmlAgilityPack it works good for me, but I got an issue with this website when I need to scrape data from another page of product list. Because link doesn't have page number so I cannot access it by changing link. I found out that page is changed by javascript "__doPostBack" function which doesn't changes the link, just reloads the page, and loads the data.
This is my code for scraping code and price of the product in this web site, however there are more products in other page e.g 2, 3, 4, 5... I need to scrape data from all of these. On other websites I can do just simply passing link to web.Load("Link"); and it works well because link is changing when you change page of product list. In this example link is not changing when other page of the list is selected.
public class CodeAndPrice
{
public string Code { get; set; }
public string Price { get; set; }
}
public partial class Form1 : Form
{
DataTable table;
HtmlWeb web = new HtmlWeb();
public Form1()
{
InitializeComponent();
InitTable();
}
private void InitTable()
{
table = new DataTable("DataTableTest");
table.Columns.Add("Code", typeof(string));
table.Columns.Add("Price", typeof(string));
dataGridView.DataSource = table;
}
private async Task<List<CodeAndPrice>> DataScraping (){
var page = await Task.Factory.StartNew(() => web.Load("https://www.kilobaitas.lt/Kompiuteriai/Plansetiniai_(Tablet)/CatalogStore.aspx?CatID=PL_626"));
var codesNodes = page.DocumentNode.SelectNodes("//td[#class='mainContent']//div[#class='itemNormal']//div[#class='itemCode']");
var pricesNodes = page.DocumentNode.SelectNodes("//td[#class='mainContent']//div[#class='itemNormal']//div[#class='itemCode']//parent::div//div[#class='itemBoxPrice']");
if (codesNodes == null || pricesNodes == null)
return new List<CodeAndPrice>();
var codes = codesNodes.Select(node => node.InnerText.Replace("kodas", "").Replace(" ", "").Replace(": ", ""));
var prices = pricesNodes.Select(node => node.InnerText.Replace(" ", "").Replace(" €", ""));
return codes.Zip(prices, (code,price)=> new CodeAndPrice() { Code = code, Price = price }).ToList();
}
private async void Form1_Load(object sender, EventArgs e)
{
var results = await DataScraping();
foreach (var rez in results) {
table.Rows.Add(rez.Code, rez.Price);
}
}
}
Passing __doPostBack('designer1$ctl11$ctl00$MainCatalogSquare1$XDataPaging1','paging.1'); into the browser's console, page 2 is loaded, by changing "paging.*", browser loads page *+1
What is the simplest way to manipulate javascript, that I will be able to change page while scraping data and scrape data from other pages of this website?

Troubles to open ajaxToolkit:ModalPopupExtender with JavaScript

I'm trying to open a ajaxToolkit:ModalPopupExtender with JavaScript but when I run my code and I call the function from the code behind this crash and show this error.
JavaScript runtime error: Unable to get property 'show' of undefined
or null reference
this is my JavaScript:
<script>
function closeChangeArea() {
$find('ModalChangeArea').hide();
}
function showChangeArea() {
$find('ModalChangeArea').show();
}
</script>
and this is my code:
protected void Btn_Click_Ch_Area(object sender, EventArgs e)
{
LinkButton lb = (LinkButton)sender;
GridViewRow gr = (GridViewRow)lb.NamingContainer;
Label ToolChange = (Label)gr.FindControl("Lbl_toolg");
Txt_Tool_Reasign.Text = ToolChange.Text;
ScriptManager.RegisterStartupScript(this, this.GetType(), "Pop", "showChangeArea();", true);
}
this is my ModalPoupExtender
<ajaxToolkit:ModalPopupExtender
ID="ModalChangeArea"
runat="server"
TargetControlID="hid"
PopupControlID="ChangeArea"
RepositionMode="RepositionOnWindowResizeAndScroll"
DropShadow="true"
PopupDragHandleControlID="moveArea">
</ajaxToolkit:ModalPopupExtender>
In asp.net control id is dynamically appended with container, in that case you will not get the control using $find to get control use clientid of asp.net control or set ClientIdMode = "Static".
Try below code to access element.
$find('<%= ModalChangeArea.ClientID %>').show();
$find('<%= ModalChangeArea.ClientID %>').hide();

Is it possible to get data from HTML forms into android while using webView?

I'm making a very simple form in HTML which is viewed in android using the webview which takes in your name using a textbox and when you click on the button, it displays it into a paragraph and it's made using both html and javascript.
This is my html code:
<!DOCTYPE html>
<html>
<body>
<p> Write your name and win your favorite game console name and win it! The winners will be announced in 4 days.</p>
Type your name here: <input id="thebox" type="text" name="value" value=""><br>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
function myFunction() {
var x = document.getElementById("thebox").value;
document.getElementById("demo").innerHTML = x;
}
</script>
</body>
</html>
NEW EDITED FORM
<form name="albert" action="" method="POST">
<label for="firstname"> First Name </label>
<br /><br />
<input type="text" name="firstname" id="firstname" />
<input type="submit" name="sbumit" value="Submit" />
</form>
I want to get the value from the input box called "thebox" in a variable in android on the button click and I tried lots of stuff before and I followed a method where you inject a JS file but since I know nothing about JS so I did fail trying that and here is the file that I put in my project and the file is called inject.js:
document.getElementsByTagName('form')[0].onsubmit = function () {
var objPWD, objAccount, objSave;
var str = '';
var inputs = document.getElementsByTagName('thebox');
for (var i = 0; i < inputs.length; i++) {
if (inputs[i].name.toLowerCase() === 'thebox') {
objAccount = inputs[i];
}
}
if(objAccount != null) {
str += objAccount.value;
}
if(objPWD != null) {
str += ' , ' + objPWD.value;
}
if(objSave != null) {
str += ' , ' + objSave.value;
}
window.AndroidInterface.processHTML(str);
return true;
};
And later as I followed that article it said that I need to put some stuff in my MainActivity but since I'm using webview for the first time, I couldn't understand much and heres the code I put into my MainActivity:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
WebView webView = new WebView(this);
this.setContentView(webView);
// enable javascript
WebSettings webSettings = webView.getSettings();
webSettings.setJavaScriptEnabled(true);
webView.addJavascriptInterface(new JavaScriptInterface(), "AndroidInterface");
// catch events
webView.setWebViewClient(new WebViewClient(){
#Override
public void onPageFinished(WebView view, String url) {
try {
view.loadUrl("javascript:" + buildInjection());
} catch (IOException e) {
e.printStackTrace();
}
}
});
webView.loadUrl("http://someurl.com");
}
A nested class that I made in my MainActivity:
class JavaScriptInterface {
#JavascriptInterface
public void processHTML(String formData) {
Log.d("AWESOME_TAG", "form data: " + formData);
}
}
And finally the method that injects the code:
private String buildInjection() throws IOException {
StringBuilder buf = new StringBuilder();
InputStream inject = getAssets().open("inject.js");// file from assets
BufferedReader in = new BufferedReader(new InputStreamReader(inject, "UTF-8"));
String str;
while ((str = in.readLine()) != null) {
buf.append(str);
}
in.close();
return buf.toString();
}
I want to get value from the html form(the-input-box) that I show in a webview in Android and is it really possible to do that and if yes how and please explain? Thanks and also please tell in what variable will I get the value.
Webview browser=(WebView)view.findViewById(R.id.webChart);
browser.getSettings().setJavaScriptEnabled(true);
browser.addJavascriptInterface(new WebAppInterface(getActivity()), "Android");
browser.loadUrl("file:///android_asset/yourHtmlFileName.html");
add this interface class, WebAppInterface
public class WebAppInterface {
Context mContext;
String data;
WebAppInterface(Context ctx){
this.mContext=ctx;
}
#JavascriptInterface
public void sendData(String data) {
//Get the string value to process
this.data=data;
}
}
your HTML code data
function loadChartData() {
var x = document.getElementById("thebox").value;
Android.sendData(x);
}
call this function when the html button click in android webview
UPDATE
1) By default javascript is disabled in webview . to enable it, get the settings of the webview and call the setJavaScriptEnabled(true); to true.
2) to create the interface between your Javascript code and your android code, you need to create Javacript interface class.
3) bind the interface between your javascript code to android code, you need to pass the reference of the interface class and an interface name that your javaScript can call to access the class.
4) pass the html file path to load into the webview(browser).
5) create the interface class like below(WebAppInterface).
see this link for more details
https://developer.android.com/guide/webapps/webview.html
6) in HTML file, create the button and add the click listener to that button and call the sendData("your value") function with interface name(Here Android).
Thats all. you can pass the value from html to your android code.
Yes you can, you can use javascript to get webpage content. Then use the webview jsInterface to return the content to you java code.
Refer this github project. and this answer and this article.
final Context myApp = this;
/* An instance of this class will be registered as a JavaScript interface */
class MyJavaScriptInterface
{
#JavascriptInterface
#SuppressWarnings("unused")
public void processHTML(String html)
{
// process the html as needed by the app
}
}
final WebView browser = (WebView)findViewById(R.id.browser);
/* JavaScript must be enabled if you want it to work, obviously */
browser.getSettings().setJavaScriptEnabled(true);
/* Register a new JavaScript interface called HTMLOUT */
browser.addJavascriptInterface(new MyJavaScriptInterface(), "HTMLOUT");
/* WebViewClient must be set BEFORE calling loadUrl! */
browser.setWebViewClient(new WebViewClient() {
#Override
public void onPageFinished(WebView view, String url)
{
/* This call inject JavaScript into the page which just finished loading. */
browser.loadUrl("javascript:window.HTMLOUT.processHTML('<head>'+document.getElementsByTagName('html')[0].innerHTML+'</head>');");
}
});
/* load a web page */
browser.loadUrl("http://lexandera.com/files/jsexamples/gethtml.html");
Hope this helps.
For forms with method "GET" you can achieve this pretty simple just by overriding shouldOverrideUrlLoading method. Following solution works only if url was loaded through webview.loadUrl() method.
private class MWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
// submit will end-up with url like "data:,?firstname=SomeInput&sbumit=Submit"
if (URLUtil.isDataUrl(url)) {
url = url.replace(":,?", ":/?"); //to be able to properly parse Uri
Uri uri = Uri.parse(url);
//here you can get params by field name
String firstname = uri.getQueryParameter("firstname");
//we handle this URL ourselves
return true;
}
return super.shouldOverrideUrlLoading(view, url);
}
}
To communicate a webView with native android,
this is a simple way :
in your js onClick on the button you should call url that contains your text, something like myPrefix://myData
and in android
webView.setWebViewClient(new WebViewClient()
{
#Override
public boolean shouldOverrideUrlLoading(final WebView view, final String url)
{
if(url.startsWith("myPrefix://"))
{
//get your data by split url
return true;
}
return false;
});
#Shariq
As many have already answered this question in a good way, but i think moreover you need clarification about how exactly data is flowing into the codes from webview to andorid so I won't waste bytes in writing that all redundant codes:
(I'm taking reference of your codes for better understanding )
Follow these steps in these codes to make better understanding:
Step 1:
We need to define some method on Android side that can accept some data from webview
#JavascriptInterface
//this 'formData' variable is going to accept the data from webview
public void processHTML(String formData) {
Log.d("AWESOME_TAG", "form data: " + formData);
}
Now the it's value will be available to java android side context.
Step 2:
here is your HTML side codes (webview).
if the URL you are accessing in webview is yours then you can easily write these codes to html page but if you are accessing some third party URL still you can inject this js code into webview simply by following line of code:
...
//partial code
webView.load("javascript:function myFunction() { var x = document.getElementById('thebox').value; Android.processHTML(x); } myFunction();";
...
So what's exactly happening here:
'x' is the variable in js holding the required value and then we are sending this 'x' variable to android context via method call Android.processHTML(x)
I hope it might help you in a better way
Yes, it is possible. Please try using the below code
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.web_view_layout);
WebView webView = (WebView) findViewById(R.id.webView);
webView.getSettings().setPluginState(WebSettings.PluginState.ON);
WebSettings webSettings = webView.getSettings();
webSettings.setJavaScriptEnabled(true);
try {
progressDialog = new ProgressDialog(ActivityName);
progressDialog.setMessage("Loading.."); progressDialog.setCancelable(false);
webView.setWebViewClient(new MyWebViewClient());
webView.loadUrl(YOUR_URL);
} catch (Exception e) {
e.toString();
}
}
private class MyWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
progressDialog.dismissProgress();
return true;
}
#Override
public void onPageFinished(WebView view, String url) {
progressDialog.dismissProgress();
}
}
You can get data from WebView by catching alert messages.
Use WebChromeClient.
mWebview = (WebView)findViewById(R.id.yourwebviewlayout);
final class YourWebChromeClient extends WebChromeClient {
#Override
public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
Toast.makeText(getApplicationContext(),
"alert message = " + message,
Toast.LENGTH_SHORT).show();
result.confirm();
return true;
}
}
mWebview.setWebChromeClient(new YourWebChromeClient());
Best js to inject have used so far, it collects data from all forms on submit
document.getElementsByTagName("form")[0].addEventListener("submit", myFunction);
function myFunction()
{
var data="";
var inputs = document.forms[0].getElementsByTagName('input');
for (var i = 0; i < inputs.length; i++) {
var field = inputs[i];
if (field.type != 'submit' && field.type != 'reset' && field.type != 'button')
data += '' + field.name + '=' + field.value+'\n';
}
window.AndroidInterface.processHTML(data);
return true;
}

ASP.NET: HtmlGenericControl <DIV> - refresh

I have a DIV element:
<div runat="server" id="path">Nothing here... yet</div>
and JavaScript which changes its content dynamically. After some actions my element looks like this (tested with Firebug, JS is ok):
<div runat="server" id="path">FirstTest - SecondTest - ThirdTest</div>
Then I'd like to save it to text file (<asp:Button runat="server"...):
<script runat="server">
void Page_Load(Object sender, EventArgs e)
{
Button1.Click += new EventHandler(this.GreetingBtn_Click);
}
void GreetingBtn_Click(Object sender, EventArgs e)
{
HtmlGenericControl path = (HtmlGenericControl)Page.FindControl("path");
Response.AddHeader("content-disposition", "attachment;filename=download.txt");
Response.ContentType = "text/plain";
Response.Write(path.InnerText);
Response.Flush();
Response.Clear();
Response.End();
}
</script>
It also works OK (SaveDialog popups, user choose location), but... in output file there's only one line "Nothing here... yet". It looks like he doesn't react to changes made by JavaScript!
How can I force him to refresh DIV, so I can always save up-to-date content?
Thanks for any help!
You could update an asp:Hidden with the new value and use that value instead on the post back. The PlaceHolder control is not designed to be a two-way control.
E.g.
function UpdateText()
{
var text = ...;
document.getElementById("<%= path.ClientID %>").innerText = text;
document.getElementById("<%= pathHidden.ClientID %>").value = text;
}

Categories