I am using jquery.printElement.js to print. When I click on print button a print window opens with print and cancel button. If I print the document or cancel the print window every thing works fine, but if I close the window with the close button in the title bar [x] than everything stops working after dispose of print window on chrome version 35.
/// <reference path="http://code.jquery.com/jquery-1.4.1-vsdoc.js" />
/*
* Print Element Plugin 1.2
*
* Copyright (c) 2010 Erik Zaadi
*
* Inspired by PrintArea (http://plugins.jquery.com/project/PrintArea) and
* http://stackoverflow.com/questions/472951/how-do-i-print-an-iframe-from-javascript-in-safari-chrome
*
* Home Page : http://projects.erikzaadi/jQueryPlugins/jQuery.printElement
* Issues (bug reporting) : http://github.com/erikzaadi/jQueryPlugins/issues/labels/printElement
* jQuery plugin page : http://plugins.jquery.com/project/printElement
*
* Thanks to David B (http://github.com/ungenio) and icgJohn (http://www.blogger.com/profile/11881116857076484100)
* For their great contributions!
*
* Dual licensed under the MIT and GPL licenses:
* http://www.opensource.org/licenses/mit-license.php
* http://www.gnu.org/licenses/gpl.html
*
* Note, Iframe Printing is not supported in Opera and Chrome 3.0, a popup window will be shown instead
*/
; (function (window, undefined) {
var document = window["document"];
var $ = window["jQuery"];
$.fn["printElement"] = function (options) {
var mainOptions = $.extend({}, $.fn["printElement"]["defaults"], options);
//iframe mode is not supported for opera and chrome 3.0 (it prints the entire page).
//http://www.google.com/support/forum/p/Webmasters/thread?tid=2cb0f08dce8821c3&hl=en
if (mainOptions["printMode"] == 'iframe') {
if ($.browser.opera || (/chrome/.test(navigator.userAgent.toLowerCase())))
mainOptions["printMode"] = 'popup';
}
//Remove previously printed iframe if exists
$("[id^='printElement_']").remove();
return this.each(function () {
//Support Metadata Plug-in if available
var opts = $.meta ? $.extend({}, mainOptions, $(this).data()) : mainOptions;
_printElement($(this), opts);
});
};
$.fn["printElement"]["defaults"] = {
"printMode": 'iframe', //Usage : iframe / popup
"pageTitle": '', //Print Page Title
"overrideElementCSS": null,
/* Can be one of the following 3 options:
* 1 : boolean (pass true for stripping all css linked)
* 2 : array of $.fn.printElement.cssElement (s)
* 3 : array of strings with paths to alternate css files (optimized for print)
*/
"printBodyOptions": {
"styleToAdd": 'padding:10px;margin:10px;', //style attributes to add to the body of print document
"classNameToAdd": '' //css class to add to the body of print document
},
"leaveOpen": false, // in case of popup, leave the print page open or not
"iframeElementOptions": {
"styleToAdd": 'border:none;position:absolute;width:0px;height:0px;bottom:0px;left:0px;', //style attributes to add to the iframe element
"classNameToAdd": '' //css class to add to the iframe element
}
};
$.fn["printElement"]["cssElement"] = {
"href": '',
"media": ''
};
function _printElement(element, opts) {
//Create markup to be printed
var html = _getMarkup(element, opts);
var popupOrIframe = null;
var documentToWriteTo = null;
if (opts["printMode"].toLowerCase() == 'popup') {
popupOrIframe = window.open('about:blank', 'printElementWindow', 'width=650,height=440,scrollbars=yes');
documentToWriteTo = popupOrIframe.document;
}
else {
//The random ID is to overcome a safari bug http://www.cjboco.com.sharedcopy.com/post.cfm/442dc92cd1c0ca10a5c35210b8166882.html
var printElementID = "printElement_" + (Math.round(Math.random() * 99999)).toString();
//Native creation of the element is faster..
var iframe = document.createElement('IFRAME');
$(iframe).attr({
style: opts["iframeElementOptions"]["styleToAdd"],
id: printElementID,
className: opts["iframeElementOptions"]["classNameToAdd"],
frameBorder: 0,
scrolling: 'no',
src: 'about:blank'
});
document.body.appendChild(iframe);
documentToWriteTo = (iframe.contentWindow || iframe.contentDocument);
if (documentToWriteTo.document)
documentToWriteTo = documentToWriteTo.document;
iframe = document.frames ? document.frames[printElementID] : document.getElementById(printElementID);
popupOrIframe = iframe.contentWindow || iframe;
}
focus();
documentToWriteTo.open();
documentToWriteTo.write(html);
documentToWriteTo.close();
_callPrint(popupOrIframe);
};
function _callPrint(element) {
if (element && element["printPage"])
element["printPage"]();
else
setTimeout(function () {
_callPrint(element);
}, 50);
}
function _getElementHTMLIncludingFormElements(element) {
var $element = $(element);
//Radiobuttons and checkboxes
$(":checked", $element).each(function () {
this.setAttribute('checked', 'checked');
});
//simple text inputs
$("input[type='text']", $element).each(function () {
this.setAttribute('value', $(this).val());
});
$("select", $element).each(function () {
var $select = $(this);
$("option", $select).each(function () {
if ($select.val() == $(this).val())
this.setAttribute('selected', 'selected');
});
});
$("textarea", $element).each(function () {
//Thanks http://blog.ekini.net/2009/02/24/jquery-getting-the-latest-textvalue-inside-a-textarea/
var value = $(this).attr('value');
//fix for issue 7 (http://plugins.jquery.com/node/13503 and http://github.com/erikzaadi/jQueryPlugins/issues#issue/7)
if ($.browser.mozilla && this.firstChild)
this.firstChild.textContent = value;
else
this.innerHTML = value;
});
//http://dbj.org/dbj/?p=91
var elementHtml = $('<div></div>').append($element.clone()).html();
return elementHtml;
}
function _getBaseHref() {
var port = (window.location.port) ? ':' + window.location.port : '';
return window.location.protocol + '//' + window.location.hostname + port + window.location.pathname;
}
function _getMarkup(element, opts) {
var $element = $(element);
var elementHtml = _getElementHTMLIncludingFormElements(element);
var html = new Array();
html.push('<html><head><title>' + opts["pageTitle"] + '</title>');
if (opts["overrideElementCSS"]) {
if (opts["overrideElementCSS"].length > 0) {
for (var x = 0; x < opts["overrideElementCSS"].length; x++) {
var current = opts["overrideElementCSS"][x];
if (typeof (current) == 'string')
html.push('<link type="text/css" rel="stylesheet" href="' + current + '" >');
else
html.push('<link type="text/css" rel="stylesheet" href="' + current["href"] + '" media="' + current["media"] + '" >');
}
}
}
else {
$("link", document).filter(function () {
return $(this).attr("rel").toLowerCase() == "stylesheet";
}).each(function () {
html.push('<link type="text/css" rel="stylesheet" href="' + $(this).attr("href") + '" media="' + $(this).attr('media') + '" >');
});
}
//Ensure that relative links work
html.push('<base href="' + _getBaseHref() + '" />');
html.push('</head><body style="' + opts["printBodyOptions"]["styleToAdd"] + '" class="' + opts["printBodyOptions"]["classNameToAdd"] + '">');
html.push('<div class="' + $element.attr('class') + '">' + elementHtml + '</div>');
html.push('<script type="text/javascript">function printPage(){focus();print();' + ((!$.browser.opera && !opts["leaveOpen"] && opts["printMode"].toLowerCase() == 'popup') ? 'close();' : '') + '}</script>');
html.push('</body></html>');
return html.join('');
};
})(window);
Is there any way to identify the close event and end it peacefully OR do not show the [x] option at the right top corner?
Hi i struggled with this for the past 3 days, and came to the conclusion of the following:
these lines:
if (mainOptions["printMode"] == 'iframe') {
if ($.browser.opera || (/chrome/.test(navigator.userAgent.toLowerCase())))
mainOptions["printMode"] = 'popup';
}
are obsoletes and they seems to cause issues in Chrome, it happens that by the time when this plugin was created, Chrome and Opera have issues when printing an iframe content.
As of today that's not longer an issue (and since Opera uses Webkit as Chrome, i must assume this also happens to work on Opera as well).
So for now removes those lines and you will notice that the print dialog will not have the blank window anymore, hence you should not have this problem.
Related
I have a scenario in which I have to get the data from php into my Unity3d c# script.When I call www.text , I get whole html page code.In Php page I have just echo the data.
void Start() {
StartCoroutine(GetText());
}
IEnumerator GetText() {
UnityWebRequest www = new UnityWebRequest("http://192.18.23.1/php/Time.php");
www.downloadHandler = new DownloadHandlerBuffer();
yield return www.Send();
if(www.isError) {
Debug.Log(www.error);
}
else {
// Show results as text
//Debug.Log(www.downloadHandler.text);
// Or retrieve results as binary data
byte[] results = www.downloadHandler.data;
txt.text = "Success # " + www.downloadHandler.text;
}
}
Edit:
Code of Time.php
<html>
<head>
<script src="jquery.min.js" type="text/javascript"></script>
<script src="mqttws31.js" type="text/javascript"></script>
<script>
function myFunction(p1, p2) {
return p1 * p2;
};
var mqtt,payload;
var value = 10;
var reconnectTimeout = 2000;
function MQTTconnect() {
if (typeof path == "undefined") {
path = '/mqtt';
}
mqtt = new Paho.MQTT.Client(
'broker',
1883,
"/mqtt",
"a:" + "abcdef" + ":" + Date.now()
);
var options = {
timeout: 3,
useSSL: false,
cleanSession: true,
onSuccess: onConnect,
onFailure: function (message) {
$('#status').val("Connection failed: " + message.errorMessage + "Retrying");
setTimeout(MQTTconnect, reconnectTimeout);
}
};
mqtt.onConnectionLost = onConnectionLost;
mqtt.onMessageArrived = onMessageArrived;
//if (username != null) {
options.userName = 'username';
options.password = 'password';
//}
mqtt.connect(options);
}
function onConnect() {
// Connection succeeded; subscribe to our topic
mqtt.subscribe('iot-2/type/+/id/+/evt', {qos: 0});
$('#topic').val('iot-2/type/" + "+" + "/id/" + "+" + "/evt');
}
function onConnectionLost(response) {
setTimeout(MQTTconnect, reconnectTimeout);
$('#status').val("connection lost: " + responseObject.errorMessage + ". Reconnecting");
};
function onMessageArrived(message) {
var topic = message.destinationName;
payload = message.payloadString;
//document.getElementById("ws").value = payload;
};
</script>
</head>
<body>
<?php
echo '<script type="text/javascript">document.write(MQTTconnect());</script>';;
$ff = $_GET['payload'];
echo $ff;
?>
</body>
</html>
Probably the best way is to use server side php code to generate the output, excluding at all html/javascript code.
Also you need to remove any html tag and use content-type as text for ensure that solution is working.
For example:
<?php
header("Content-Type: text/plain");
echo 'result';
?>
I am using HtmlAgilityPack and C# in order to convert older IE tags as well as Javascript to be compatible with other browsers. Here is an example:
Old code:
<script for="thisForm" event="onsubmit()" language="JScript">
var Checked = false
var Counter = 0
for (;Counter < this.choice.length; Counter++)
{
if (this.choice[Counter].checked)
{
Checked = true
this.action = this.choice[Counter].value
}
}
if (!Checked)
{
alert ("Please make a selection")
return false
}
</script>
I convert to:
<script ftype="text\JScript">
function thisForm_onsubmit(el)
{
var Checked = false
var Counter = 0
for (;Counter < el.choice.length; counter++)
{
if (el.choice[counter].checked)
{
checked = true
el.action = el.choice[counter].value
}
}
if (!checked)
{
alert ("please make a selection")
return false
}
}
</script>
What I did above is removed for, event, and language attributes from script tag, added type="text/JScript" attribute and wrapped the javascript into a function code.
I do it by simply additing HtmlNode attributes and then replacing InnerHtml property value. So far it worked fine for me untill I encountered the above function. somehow instead of giving me the result above, I get the following:
<script type="text/JScript">
function thisForm_onsubmit(el)
{
var Checked = false
var Counter = 0
for (;Counter < el.choice.length; counter++)
{
if (el.choice[counter].checked)
{
checked = true
el.action = el.choice[counter].value
}
}
if (!checked)
{
alert ("please make a selection")
return false
}
}
el.choice.length;="" counter++)="" {="" if="" (el.choice[counter].checked)="" {="" checked="true" el.action="el.choice[Counter].value" }="" }="" if="" (!checked)="" {="" alert="" ("please="" make="" a="" selection")="" return="" false="" }="" }=""></ el.choice.length; counter++)
{
if (el.choice[counter].checked)
{
checked = true
el.action = el.choice[counter].value
}
}
if (!checked)
{
alert ("please make a selection")
return false
}
}
></script>
The strange part that the text I am assigning to the InnerHtml is correct, but scriptNode.InnerHtml shows different value
Here is my C# code:
if (scriptNode.Attributes["for"] != null)
{
{
if (scriptNode.Attributes["for"] != null)
ctrl = scriptNode.Attributes["for"].Value;
if (scriptNode.Attributes["event"] != null)
evt = scriptNode.Attributes["event"].Value;
if (scriptNode.Attributes["type"] != null)
typ = scriptNode.Attributes["type"].Value;
if (scriptNode.Attributes["language"] != null)
lang = scriptNode.Attributes["language"].Value;
if (scriptNode.InnerHtml != null)
code = scriptNode.InnerHtml;
func_name = ctrl + "_" + evt;
if (ctrl != "window")
new_script = Environment.NewLine + "function " + RemoveBrackets(func_name) + "(el)" + Environment.NewLine;
else
new_script = Environment.NewLine + "function " + AddBrackets(RemoveBrackets(func_name)) + Environment.NewLine;
new_script += "{" + Environment.NewLine;
new_script += "\r\n" + ReplaceThis(sFile, ctrl, evt, code, "this", "el") + "\r\n" + "}" + "\r\n";
//remove for and event attributes
scriptNode.Attributes["for"].Remove();
scriptNode.Attributes["event"].Remove();
//remove depraciated "language" attribute
//and replace it with "type" attribute
if (scriptNode.Attributes["language"] != null)
scriptNode.Attributes["language"].Remove();
if (scriptNode.Attributes["type"] == null)
scriptNode.Attributes.Add("type", "text/" + lang);
//replace old javascript with a function code
//HERE new_script variable contains the correct value but when I check scriptNode.InnerHtml after assignment, it shows the messed up code.
scriptNode.InnerHtml = new_script;
It is very strange and I can't seem to find a solution.
I have tried using HtmlEncode
scriptNode.InnerHtml = HtmlDocument.HtmlEncode(new_script);
And that produced the correct script, as specified above in second example, but replaced all the < and > with < and > etc.
So the result was:
<script type="text/JScript">
function thisForm_onsubmit(el)
{
var Checked = false
var Counter = 0
for (;Counter < el.choice.length; Counter++)
{
if (el.choice[Counter].checked)
{
Checked = true
el.action = el.choice[Counter].value
}
}
if (!Checked)
{
alert ("Please make a selection")
return false
}
}
</script>
I thought of using InnerText instead of InnerHtml, which makes more sense since what I am changing is not really HTML but InnerText property is read-only.
Can anyone shed some light on why this is happening and if there is a workaround?
The modified script contains special character < which I really suspect caused the problem. < can easily misinterpreted as first character of an opening HTML tag, especially when it is used via InnerHtml property.
Here is one possible workaround. Assume that new_script is a string variable containing the modified Javascript, including the opening and closing tags (<script type="text/JScript"></script>). You can try to load new_script into a new HtmlDocument. Then replace the old script in the 1st
HtmlDocument with the new script from the 2nd HtmlDocument instance :
.....
var newDoc = new HtmlDocument();
newDoc.LoadHtml(new_script);
var newScript = newDoc.DocumentNode.SelectSingleNode("//script");
scriptNode.ParentNode.ReplaceChild(newScript, script);
dotnetfiddle demo
Special keys such as TAB, DEL, Ctrl+C, Ctrl+V, function keys, etc. do not work in my C# Windows Forms code, which has a WebBrowser control.
These keys work fine in an ordinary Windows forms application with a WebBrowser control. However I am attempting to do something a little different:
Provide a C# DLL, which a non-GUI application can use to show the Windows Form.
In order not to block the caller, the form is created and shown in a new STA thread.
For thread safety, the Document.InvokeScript function is called via a MethodInvoker.
It's not clear which of the above aspects (if any) causes the special keystrokes to be eaten.
I have consulted the following, which don't seem to answer this question.
How to enable special keys (ctrl-c, ctrl-v, tab, delete) Windows.Form.WebBrowser Control
How do I make the Delete key work in the WebBrowser control
WebBrowser "steals" KeyDown events from my form
In particular:
Setting WebBrowserShortcutsEnabled = true does not help.
Setting the WebBrowser's Url before showing the form does not help.
The HTML and JavaScript are as follows:
<!DOCTYPE html>
<html lang='en'>
<head>
<title>Keyboard Test</title>
<meta charset='utf-8'>
<script>
document.onkeydown = function (e) {
var keyCodes = document.getElementById('keyCodes');
keyCodes.innerHTML += e.keyCode + ', ';
}
function JavaScriptFn(arg) {
alert('JavaScriptFn received arg: ' + arg);
}
function CallCSharp() {
if (window.external && window.external.SupportsAcmeAPI) {
var str = window.external.CSharpFn('JavaScript says hello');
alert('C# returned: ' + str);
}
else {
alert('Browser does not support the Acme C# API.')
}
}
</script>
</head>
<body>
<select autofocus>
<option>ABC</option>
<option>DEF</option>
</select><br>
<input type='text'><br>
<button onclick='CallCSharp();'>Press to Call C#</button>
<p>Press TAB, DEL, Ctrl, etc. to test keyboard support.</p>
<p id='keyCodes'>Key codes detected: </p>
</body>
</html>
The document.onkeydown handler defined in the script above does work when the HTML is loaded in an ordinary browser. All of the special keys work fine in that scenario.
The C# test code is as follows:
// Compile and test as follows (changing paths as needed):
// set DOTNET=C:\Windows\Microsoft.NET\Framework\v4.0.30319
// set REF="C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.0\WindowsBase.dll"
// %DOTNET%\csc -r:%REF% TestProgram.cs
// TestProgram.exe
using System;
using System.IO;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Windows.Threading; // WindowsBase.dll
using System.Windows.Forms;
namespace TestProgram
{
class TestProgram
{
static void Main()
{
// Write the test HTML file.
var htmlFile = System.IO.Path.GetTempPath() + "temp.html";
File.WriteAllText(htmlFile, GetTestHTML());
// Show the Windows form with the WebBrowser control.
var wrapper = new FormWrapper(htmlFile);
wrapper.Run();
// Call one of the HTML file's JavaScript functions.
var script = "JavaScriptFn";
var scriptArgs = new object[] {"C# says hello."};
if (! wrapper.CallJavaScript(script, scriptArgs))
{
MessageBox.Show("An error occurred when calling JavaScript.");
}
// What would be a clean way of terminating wrapper's thread?
Console.WriteLine("Press Ctrl+C to exit ...");
}
static string GetTestHTML()
{
return "<!DOCTYPE html>\r\n"
+ "<html lang='en'>\r\n"
+ "<head>\r\n"
+ "<title>Keyboard Test</title>\r\n"
+ "<meta charset='utf-8'>\r\n"
+ "<script>\r\n"
+ " document.onkeydown = function (e) {\r\n"
+ " var keyCodes = document.getElementById('keyCodes');\r\n"
+ " keyCodes.innerHTML += e.keyCode + ', ';\r\n"
+ " }\r\n"
+ " function JavaScriptFn(arg) {\r\n"
+ " alert('JavaScriptFn received arg: ' + arg);\r\n"
+ " }\r\n"
+ " function CallCSharp() {\r\n"
+ " if (window.external && window.external.SupportsAcmeAPI) {\r\n"
+ " var str = window.external.CSharpFn('JavaScript says hello');\r\n"
+ " alert('C# returned: ' + str);\r\n"
+ " }\r\n"
+ " else {\r\n"
+ " alert('Browser does not support the Acme C# API.')\r\n"
+ " }\r\n"
+ " }\r\n"
+ "</script>\r\n"
+ "</head>\r\n"
+ "<body>\r\n"
+ "<select autofocus>\r\n"
+ " <option>ABC</option>\r\n"
+ " <option>DEF</option>\r\n"
+ "</select><br>\r\n"
+ "<input type='text'><br>\r\n"
+ "<button onclick='CallCSharp();'>Press to Call C#</button>\r\n"
+ "<p>Press TAB, DEL, Ctrl, etc. to test keyboard support.</p>\r\n"
+ "<p id='keyCodes'>Key codes detected: </p>\r\n"
+ "</body>\r\n"
+ "</html>\r\n";
}
}
public class FormWrapper
{
private Form1 form;
private string htmlFile;
public FormWrapper(string htmlFile)
{
this.htmlFile = htmlFile;
}
public void Run()
{
// Set up a thread in which to show the Windows form.
Thread thread = new Thread(delegate()
{
// Set up the Windows form, and show it.
form = new Form1(htmlFile);
form.Width = 400;
form.Show();
// Process the event queue in a loop.
System.Windows.Threading.Dispatcher.Run();
});
// The thread must run in a single-threaded apartment.
thread.SetApartmentState(ApartmentState.STA);
// Start the thread.
thread.Start();
}
public bool CallJavaScript(string script, object[] args)
{
var success = false;
for (int i = 0; i < 10; ++i)
{
if (form == null)
{
// Perhaps the form is in the process of being created?
Thread.Sleep(100);
}
else
{
success = form.CallJavaScript(script, args);
break;
}
}
return success;
}
}
public class Form1 : Form
{
private WebBrowser browser;
public Form1(string htmlFile)
{
browser = new WebBrowser();
browser.Dock = DockStyle.Fill;
browser.Url = new Uri(htmlFile);
browser.ObjectForScripting = new ScriptingObject();
browser.WebBrowserShortcutsEnabled = true; // Does not help.
Controls.Add(browser);
}
// CallJavaScript: Intended to be a thread-safe call to a JavaScript
// function in the form's WebBrowser control's HTML document.
// REFERENCES:
// https://stackoverflow.com/questions/315938/webbrowser-document-cast-not-valid
// http://msdn.microsoft.com/en-us/library/system.windows.forms.htmldocument.invokescript(v=vs.100).aspx
// http://msdn.microsoft.com/en-us/library/system.windows.forms.methodinvoker(v=vs.100).aspx
public bool CallJavaScript(string script, object[] args)
{
if (!this.IsHandleCreated && !this.IsDisposed)
{
return false;
}
else
{
this.Invoke(new MethodInvoker(()=>browser.Document.InvokeScript(script, args)));
return true;
}
}
}
[ComVisible(true)]
public class ScriptingObject
{
// SupportsAcmeAPI: Visible to JavaScript as window.external.SupportsAcmeAPI.
public bool SupportsAcmeAPI()
{
return true;
}
// CSharpFn: Visible to JavaScript as window.external.CSharpFn.
public string CSharpFn(string arg)
{
MessageBox.Show("CSharpFn received arg: " + arg);
return "Hello, JavaScript.";
}
}
}
Any advice would be appreciated!
If you change:
System.Windows.Threading.Dispatcher.Run();
to
Application.Run(form);
and also the document.onkeydown to:
String html =
#"
//...
document.onkeydown = function (e) {
var keyCodes = document.getElementById('keyCodes');
e = e || window.event;
var kc = (e.charCode ? e.CharCode : (e.which) ? e.which : e.keyCode);
keyCodes.innerHTML += kc + ', ';
}
//...
";
Then it works. (Side note: You can use a continuous string block #"..." instead of "...\r\n" +)
I want to make a multiple upload, iam using some script from this forum.
the scripts is perfectly works, but when i merge it with my project.
javascript can't get the value of my element.
i found out the problem is because i have many ID PANEL in the page, i need to change to getElementByID('<%="FileUpdate.ClientID%>').value (the original : getElementByID("FileUpdate").value)
THE PROBLEM IS :
I have to use counter, ex: getElementByID('<%="txtFileUpdate' + counter + '%>').value but it FAIL.
the error says "too many characters in character literal" pointing to that line.
Please someone help, is there any solution for this problem ?
Here is the script
-----> Error " to many characters in character literal"
<script type="text/javascript" language="javascript">
var counter = 1;
function AddFileUpload() {
if (counter < 5) {
counter++;
var div = document.createElement('DIV');
div.innerHTML = '<input id="FileUpload' + counter + '" name = "file' + counter +
'" type="file" />' +
'<input id="Button' + counter + '" type="button" ' +
'value="Remove" onclick = "RemoveFileUpload(this)" />';
document.getElementById("FileUploadContainers").appendChild(div);
}
else {
alert("Cannot attach more than 5 file");
}
}
function GetFile() {
var temp;
var error = "";
var stringx = "";
var exCounter = 1 ;
for (exCounter; exCounter <= counter; exCounter++) {
-----> stringx = document.getElementById('<%=FileUpload'+exCounter+'.ClientID%>').value;
if (stringx != "")
temp += stringx + "#;";
else
error += exCounter + ", ";
}
if (error != "") {
alert("Field " + error + " Still Empty");
return;
}
document.getElementById('<%=HiddenField1.ClientID%>').value = temp;
}
Try this:
getElementByID('FileUpdate<%=counter%>').value
or
getElementByID('<%=txtFileUpdate + counter.ToString()%>').value
Here is my PhantomJS test project which I run in cmd.exe by typing (for example):
>phantomjs.exe abacus.js 1111 222
name: 1111
pass: 222
load started
load finished
jQuery loaded
console> name:
console> pass: undefined
step 0
step 1
done
Abacus.js:
var name, pass;
if (phantom.args.length !== 2) {
console.log('not enough arguments!');
phantom.exit();
} else {
name = phantom.args[0];
pass = phantom.args[1];
}
console.log("name: " + name); //output: "name: MyUsername"
console.log("pass: " + pass); //output: "pass: MyPassword"
var stepIndex = 0;
var page = new WebPage();
var loadInProgress = true;
var jQueryLoad = false;
page.onConsoleMessage = function (msg, line, source) {
console.log('console> ' + msg);
};
page.onAlert = function (msg) {
console.log('alert> ' + msg);
};
page.onLoadStarted = function () {
loadInProgress = true;
console.log("load started");
};
page.onLoadFinished = function () {
loadInProgress = false;
console.log("load finished");
jQueryLoad = page.injectJs("jquery-1.7.1.min.js");
if (jQueryLoad)
console.log('jQuery loaded');
};
var interval = setInterval(function () {
if (jQueryLoad && !loadInProgress && typeof steps[stepIndex] == "function") {
steps[stepIndex]();
page.render("step " + stepIndex + ".png");
console.log("step " + stepIndex++);
}
if (typeof steps[stepIndex] != "function") {
console.log("done");
phantom.exit();
}
}, 1000);
var steps = [
function () {
page.evaluate(function () {
console.log("name: " + this.name); //output: "console> name:"
console.log("pass: " + this.pass); //output: "console> pass: undefined"
var arr = document.frmMain;
if (arr !== null) {
arr.elements["username"].value = "MyUsername"; //Only fils in form if it's a string literal
arr.elements["password"].value = "MyPassword";
} else {
console.log("Could not find frmMain");
}
});
}, function () {
page.evaluate(function () {
document.frmMain.submit();
});
} ];
page.open("http://www.abacusdatagraphics.com/");
page.viewportSize = { width: 1280, height: 1024 };
Any help would be appreciated as to why phantom.args & name/pass suddenly lose their values.
I am running cmd.exe in C# since the name and password change every now and then and are kept in a database. This is simply a small test program to see if it can be done.
(Also, thanks to Stack Overflow for giving me most of this code in the first place)
#jlafay
The solution I used from this is as such:
PhantomJS wasn't able to fill in the forms with variables because page.evaluate can't handle parameters so when filling out the form, the variables (and the forms) are null.
So instead I treated function() as a string and passed the variables like this:
page.evaluate('function () {' +
'var theName = ' + name + ';' +
'var thePass = ' + pass + ';' +
'console.log(\"name: \" + this.name);' + //output: "console> name:"
'console.log(\"pass: \" + this.pass);' + //output: "console> pass: undefined"
'var arr = document.frmMain;' +
'if (arr !== null) {' +
' arr.elements["username"].value = theName;' +
' arr.elements["password"].value = thePass;' +
'} else {' +
' console.log("Could not find frmMain");' +
'}' +
'}');
Or something like that, I don't have the code anymore.