JavaScript Chrome printing multiple screens - javascript

problem in Chrome printing multiple screens
the code below is designed to load records from a list of students and print the resulting screen for each student.
this works fine in browsers other than Chrome
Chrome does not display each students record result and thus prints multiple copies of just one student.
When the script finishes the last student record in the list is displayed so we know that the form request is being made successfully. It appears Chrome is not waiting for the form request to load or that it doesn't update the screen before getting to the print command.
function printAll() {
var stdsObj = document.getElementById('stds');
for ( var i = 0; i < stdsObj.options.length; i++ ) {
showRec(i)
printIframe("main")
}
}
function showRec(selRec) {
var recID = '';
var recName = '';
var recNum = '';
var stdsObj = document.getElementById('stds');
recID = stdsObj.options[selRec].value;
recName = stdsObj.options[selRec].text;
recNum = selRec +1;
document.getElementById('recID').value = recID;
document.getElementById('recName').value = recName;
document.getElementById('recNum').value = recNum;
document.getElementById('noCacheRec').value = Math.random();
document.recList.submit()
}
function printIframe(id) {
var iframe = document.frames ? document.frames[id] : document.getElementById(id);
var ifWin = iframe.contentWindow || iframe;
ifWin.focus();
ifWin.printMe();
return false;
}
The form recList loads data into iframe "main"
<form id="recList" name="recList" action="ru_cse_view.pl" target="main">
printMe is a function in the iframe "main" that prints the iframe
function printMe() {
window.print()
}

Related

Why doesn't this chrome extension work?

I want to collect the url (var name is 'url') of a webpage into a variable in a chrome extension, together with several user inputs in text inputs, and to send it to a remote php script for processing into an sql database. I am using AJAX to make the connection to the remote server. The popup.html contains a simple form for UI, and the popup.js collects the variables and makes the AJAX connection. If I use url = document.location.href I get the url of the popup.html, not the page url I want to process. I tried using chrome.tabs.query() to get the lastFocusedWindow url - the script is below. Nothing happens! It looks as though it should be straightforward to get lastFocusedWindow url, but it causes the script to fail. The manifest.json sets 'tabs', https://ajax.googleapis.com/, and the remote server ip (presently within the LAN) in permissions. The popup.html has UI for description, and some tags. (btw the response also doesn't work, but for the moment I don't mind!)
//declare variables to be used globally
var url;
// Get the HTTP Object
function getHTTPObject(){
if (window.ActiveXObject) return new ActiveXObject("Microsoft.XMLHTTP");
else if (window.XMLHttpRequest) return new XMLHttpRequest();
else {
alert("Your browser does not support AJAX.");
return null;
}
// Change the value of the outputText field THIS PART IS NOT WORKING YET
function setOutput(){
if(httpObject.readyState == 4){
//document.getElementById('outputText').value = httpObject.responseText;
"Bookmark added to db" = httpObject.responseText; // does this work?
}
}
//put URL tab function here
chrome.tabs.query(
{"active": true, "lastFocusedWindow": true},
function (tabs)
{
var url = tabs[0].url; //may need to put 'var' in front of 'url'
}
);
// Implement business logic
function doWork(){
httpObject = getHTTPObject();
if (httpObject != null) {
//get url? THIS IS OUTSTANDING - url defined from chrome.tabs.query?
description = document.getElementById('description').value;
tag1 = document.getElementById('tag1').value;
tag2 = document.getElementById('tag2').value;
tag3 = document.getElementById('tag3').value;
tag4 = document.getElementById('tag4').value;
httpObject.open("GET", "http://192.168.1.90/working/ajax.php?url="+url+"&description="+description+"&tag1="+tag1+"&tag2="+tag2+"&tag3="+tag3+"&tag4="+tag4, true);
httpObject.send(null);
httpObject.onreadystatechange = setOutput(); //THIS PART IS NOT WORKING
finalString = httpObject.responseText; //NOT WORKING
return finalString; //not working
} //close if
} //close doWork function
var httpObject = null;
var url = null;
var description = null;
var tag1 = null;
var tag2 = null;
var tag3 = null;
var tag4 = null;
// listens for button click on popup.html
document.addEventListener('DOMContentLoaded', function () {
document.querySelector('button').addEventListener('click', doWork);
});
Having no responses I first used a bookmarklet instead. The bookmarklet passes the url and title to a php script, which enters them into a db before redirecting the user back to the page they were on.
javascript:(function(){location.href='http://[ipaddress]/bookmarklet.php?url='+encodeURIComponent(location.href)+'&description='+encodeURIComponent(document.title)})()
Then I found this code which works a treat.
var urlOutput = document.getElementById('bookmarkUrl');
var titleOutput = document.getElementById('bookmarkTitle');
if(chrome) {
chrome.tabs.query(
{active: true, currentWindow: true},
(arrayOfTabs) => { logCurrentTabData(arrayOfTabs) }
);
} else {
browser.tabs.query({active: true, currentWindow: true})
.then(logCurrentTabData)
}
const logCurrentTabData = (tabs) => {
currentTab = tabs[0];
urlOutput.value = currentTab.url;
titleOutput.value = currentTab.title;
}

UPDATED: redirect url pass parameter from another page

I'm would like to do a 2 step process without the user knowing. Right now when the user click on the link from another page.
URL redirect to run some JavaScript function that updates the database.
Then pass the variable to view a document.
User clicks on this link from another page
Here is some of code in the JavaScript file:
<script type="text/javascript">
window.onload = function(){
var auditObject ="";
var audit_rec = {};
var redirLink = "";
if(document.URL.indexOf('?1w') > -1 {
redirLink = "https://www.wikipedia.org/";
auditObject = redirLink;
audit_rec.action = "OPEN";
audit_rec.object = auditObject;
audit_rec.object_type = "WINDOW";
audit_rec.status = "Y";
window.open(redirLink);
} else {
audit_rec.target = /MyServlet;
audit_rec.action = "OPEN";
audit_rec.object = TESTSITE;
audit_rec.object_type = "WINDOW";
audit_rec.status = "Y";
}
function audit(audit_rec) {
var strObject = audit_rec.object;
strObject = strObject.toLowerCase();
var strCategory = "";
if (strObject.indexOf("wiki") > -1) {
strCategory = "Wiki";
} else if strObject.indexOf("test") > -1) {
strCategory = "TEST Home Page";
}
//Send jQuery AJAX request to audit the user event.
$.post(audit_rec.target, {
ACTION_DATE : String(Date.now()),
DOMAIN : "TESTSITE",
ACTION : audit_rec.action,
OBJECT : audit_rec.object,
OBJECT_TYPE : audit_rec.object_type,
STATUS : audit_rec.status
});
}
//TEST initial page load.
audit(audit_rec);
}
</script>
Can someone help? Thanks
You could give your link a class or ID such as
<a id="doclink" href="http://website.com/docviewer.html?docId=ABC%2Fguide%3A%2F%2F'||i.guide||'">'||i.docno||'</a>
then use javascript to intercept it and run your ajax script to update the database. Here's how you'd do it in jQuery:
$('#doclink').click(function(e) {
var linkToFollow = $(this).attr('href');
e.preventDefault();
yourAjaxFunction(parameters, function() {
location.href = linkToFollow;
});
});
where the function containing the redirect is a callback function after your ajax script completes. This stops the link from being followed until you've run your ajax script.
if your question is to hide the parameters Here is the Answer
you just use input type as hidden the code like this
'||i.docno||'

Submitting inputs without forms with

I am trying to edit my table rows (img: http://imgur.com/yTpfCIc ) and POST the changed data to my edit.php file. I am trying to do this via jQuery. But when I click save button nothing happens, this is the explained javascript:
//Getting all "Edit" buttons in the table (one for each row)
var buttons = document.getElementsByClassName("clicker");
var savebutton = function(id){
//Alert the Id of the button to see if the function is being called, and it is.
alert(id);
//If I have any $_POST["action"] different from "update" or "edit" I should get redirected to a page apologizing, saying this cant happen. But nothing happens. (not problem with edit.php, because already tried via another way of posting from another page)
$.post( "edit.php", { action: "test"} );
};
var buttonclicked = function(e){
if(e.target.textContent == "Edit")
{
//In this function I create a lot of inputs that you see in the picture and cannot be submited one at a time
e.target.textContent = "Cancel";
var id = e.target.id;
var editable_elements = document.querySelectorAll("[contenteditable=false]");
var sub = document.getElementById("sub"+id);
var j = document.createElement("input");
j.setAttribute("type", "text");
j.setAttribute("name", "subject");
j.setAttribute("value", sub.textContent);
j.setAttribute("placeholder", sub.textContent);
j.setAttribute("style", "width: 150px");
j.textContent = sub.textContent;
sub.innerHTML = "";
sub.appendChild(j);
for(var k = (id*6); k < (id*6)+6; k++){
var l = k;
var index = k -(k*id) + 1;
l = document.createElement("input");
l.setAttribute('type',"number");
l.setAttribute("style", "width: 75px");
l.setAttribute("step", "0.01");
if(index <= 4){
l.setAttribute('name',"g"+index);
l.setAttribute('placeholder',"G"+index);
l.setAttribute("value", editable_elements[k].textContent);
}
else if(index == 5){
l.setAttribute('name',"creditos");
l.setAttribute('placeholder',"credits");
l.setAttribute("value", editable_elements[k].textContent);
}
else if(index == 6){
l.setAttribute('name',"criteria");
l.setAttribute('placeholder',"criteria");
l.setAttribute("value", editable_elements[k].textContent);
}
editable_elements[k].innerHTML = "";
editable_elements[k].appendChild(l);}
//If any edit button is pressed, create a save button in the same row
var s = document.createElement("input");
s.textContent = "Save";
s.setAttribute('type',"button");
s.setAttribute('value',"update");
s.setAttribute("id", id);
s.setAttribute("name", "a");
//Call the function that is supposed to POST all inputs infotmations
s.setAttribute("onclick", "savebutton(this.id)");
var clickbutton = document.getElementById("save"+id);
clickbutton.appendChild(s);
}
else //save button has been clicked
{
//nothing
}
};
//If one of those buttons is clicked call the function
for(var j = 0; j < buttons.length; j++)
{
buttons[j].addEventListener('click', buttonclicked);
}
That is my problem...
If you want to see the whole page, its here: http://pastie.org/10578782
You have this comment in your code:
//If I have any $_POST["action"] different from "update" or "edit" I
should get redirected to a page apologizing, saying this cant happen.
But nothing happens. (not problem with edit.php, because already tried
via another way of posting from another page)
$.post( "edit.php", { action: "test"} );
When you post via ajax, redirects do not work. Open the dev tools in your browser and check the network traffic. I'm pretty sure the edit.php page is being posted to. You need to use a callback function to check the response of the post action and act accordingly, example:
$.post( "edit.php", { action: "test"}, function(data) {
//data is the response from the edit.php
alert(data);
});
Try this code and see what the alert box says. If you want to "redirect", you can use document.location.href = 'whatever.php'; inside the callback in place of the alert(); statement.

xpages JSON-RPC Service handling response from callback funciton

I have a slickgrid screen (on regular Domino form) wherein user can select and update some documents. I needed to show a pop-up displaying status of every selected document so I created an XPage. In my XPage I am looping through selected documents array (json) and call an RPC method for every document. Code to call RPC method is in a button which is clicked on onClientLoad event of XPAGE. RPC is working fine because documents are being updated as desired. Earlier I had RPC return HTML code for row () which was being appended to HTML table. It works in Firefox but not in IE. Now I am trying to append rows using Dojo but that’s not working either.
Here is my Javascript code on button click.
var reassign = window.opener.document.getElementById("ResUsera").innerHTML;
var arr = new Array();
var grid = window.opener.gGrid;
var selRows = grid.getSelectedRows();
for (k=0;k<selRows.length;k++)
{
arr.push(grid.getDataItem(selRows[k]));
}
var tab = dojo.byId("view:_id1:resTable");
while (arr.length > 0)
{
var fldList = new Array();
var ukey;
var db;
var reqStatusArr = new Array();
var docType;
var docno;
ukey = arr[0].ukey;
db = arr[0].docdb;
docType = arr[0].doctypeonly;
docno = arr[0].docnum;
fldList.push(arr[0].fldIndex);
reqStatusArr.push(arr[0].reqstatusonly);
arr.splice(0,1)
for (i=0;i < arr.length && arr.length>0;i++)
{
if ((ukey == arr[i].ukey) && (db == arr[i].docdb))
{
fldList.push(arr[i].fldIndex);
reqStatusArr.push(arr[i].reqstatusonly);
arr.splice(i,1);
i--;
}
}
console.log(ukey+" - "+db+" - "+docno+" - "+docType);
var rmcall = faUpdate.updateAssignments(db,ukey,fldList,reassign);
rmcall.addCallback(function(response)
{
require(["dojo/html","dojo/dom","dojo/domReady!"],function(html,dom)
{
var tbdy = dom.byId("view:_id1:resTable").getElementsByTagName("tbody");
html.set(tbdy,
tbdy.innerHTML+"<tr>"+
"<td>"+docType+"</td>"+
"<td>"+docno+"</td>"+
"<td>"+reqStatusArr.join("</br>")+"</td>"+
"<td>"+response+"</td></tr>"
);
});
});
}
dojo.byId("view:_id1:resTable").style.display="inline";
dojo.byId("idLoad").style.display="none";
RPC Service Code
<xe:jsonRpcService
id="jsonRpcService2"
serviceName="faUpdate">
<xe:this.methods>
<xe:remoteMethod name="updateAssignments">
<xe:this.arguments>
<xe:remoteMethodArg
name="dbPth"
type="string">
</xe:remoteMethodArg>
<xe:remoteMethodArg
name="uniquekey"
type="string">
</xe:remoteMethodArg>
<xe:remoteMethodArg
name="fieldList"
type="list">
</xe:remoteMethodArg>
<xe:remoteMethodArg
name="reassignee"
type="string">
</xe:remoteMethodArg>
</xe:this.arguments>
<xe:this.script><![CDATA[print ("starting update assignments from future assignments page");
var db:NotesDatabase = null;
var vw:NotesView = null;
var doc:NotesDocument = null;
try{
db=session.getDatabase("",dbPth);
if (null!= db){
print(db.getFileName());
vw = db.getView("DocUniqueKey");
if (null!=vw){
print ("got the view");
doc = vw.getDocumentByKey(uniquekey);
if (null!=doc)
{
//check if the document is not locked
if (doc.getItemValueString("DocLockUser")=="")
{
print ("Got the document");
for (i=0;i<fieldList.length;i++)
{
print (fieldList[i]);
doc.replaceItemValue(fieldList[i],reassignee);
}
doc.save(true);
return "SUCCESS";
}
else
{
return "FAIL - document locked by "+session.createName(doc.getItemValueString("DocLockUser")).getCommon();
}
}
else
{
return "FAIL - Contact IT Deptt - Code: 0";
}
}
else
{
return "FAIL - Contact IT Deptt - Code: 1";
}
}
else
{
return "FAIL - Contact IT Deptt - Code: 2";
}
}
catch(e){
print ("Exception occured --> "+ e.toString());
return "FAIL - Contact IT Deptt - Code: 3";
}
finally{
if (null!=doc){
doc.recycle();
vw.recycle();
db.recycle();
}
}]]></xe:this.script>
</xe:remoteMethod>
</xe:this.methods>
</xe:jsonRpcService>
Thanks in advance
I have resolved this issue. First, CSJS variables were not reliably set in callback function so I made RPC return the HTML string I wanted. Second was my mistake in CSJS. I was trying to fetch tbody from table using
var tbdy = dom.byId("view:_id1:resTable").getElementsByTagName("tbody");
where as it returns an array so it should have been
var tbdy = dom.byId("view:_id1:resTable").getElementsByTagName**("tbody")[0]**;
also I moved tbody above while loop. I can post entire code if anyone is interested!!

Javascript code not displaying wanted output

I've written some code to display my favorites in IE8 but for an unknown reason I have no output on the screen despite the fact that my page is accepted by IE and that the test text 'this is a test' is displayed.
my code :
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso 8859-1" />
<script type="text/javascript">
var i = 0;
var favString = "";
var fso;
function GetFavourites(Folder) {
var FavFolder = fso.GetFolder(Folder);
//Gets Favourite Names & URL's for given folder.
var files = new Enumerator(FavFolder.Files);
for (; !files.atEnd(); files.moveNext()) {
var fil = files.item();
if (fil.Type == "Internet Shortcut") {
var textReader = fso.OpenTextFile(fil.Path, 1, false, -2);
var favtext = textReader.ReadAll();
var start = favtext.indexOf("URL", 16);
var stop = favtext.indexOf("\n", start);
favString += fil.Name.replace(/.url/, "");
favString += ":URL:";
//to separate favourite name & favorite URL
favString += favtext.substring(start + 4, stop - 1);
favorites.innerHTML += favString; // Not working !
favorites.innerHTML += 'test'; // Not working too !
favString += ":NEXT:"; //to separate favorites.
i++;
}
}
//Checks any subfolder exists
var subfolders = new Enumerator(FavFolder.SubFolders);
for (; !subfolders.atEnd(); subfolders.moveNext()) {
var folder = subfolders.item();
GetFavourites(folder.Path);
}
}
function Import() {
try {
fso = new ActiveXObject("Scripting.FileSystemObject");
if (fso !== null) {
//Create windows script shell object to access Favorites folder in user system.
var object = new ActiveXObject("WScript.Shell");
var favfolderName = object.SpecialFolders("Favorites");
if (favString === "") {
GetFavourites(favfolderName);
}
}
}
catch (err) {
alert("Security settings to be modified in your browser ");
}
}
</script>
</head>
<body onload="Import()">
<p>this is a test</p> <!-- Working ! -->
<div id="favorites">
</div>
</body>
</html>
The following works for me:
var fso, favs = [];
function GetFavourites(Folder) {
var FavFolder = fso.GetFolder(Folder);
//Gets Favourite Names & URL's for given folder.
var files = new Enumerator(FavFolder.Files);
for (; !files.atEnd(); files.moveNext()) {
var fil = files.item();
if (fil.Type == "Internet Shortcut") {
var textReader = fso.OpenTextFile(fil.Path, 1, false, -2);
var favtext = textReader.ReadAll();
var start = favtext.indexOf("URL", 16);
var stop = favtext.indexOf("\n", start);
favString = fil.Name.replace(/.url/, "");
favString += ":URL:";
//to separate favourite name & favorite URL
favString += favtext.substring(start + 4, stop - 1);
favs.push(favString);
}
}
//Checks any subfolder exists
var subfolders = new Enumerator(FavFolder.SubFolders);
for (; !subfolders.atEnd(); subfolders.moveNext()) {
var folder = subfolders.item();
GetFavourites(folder.Path);
}
}
function Import() {
try {
fso = new ActiveXObject("Scripting.FileSystemObject");
if (fso !== null) {
//Create windows script shell object to access Favorites folder in user system.
var object = new ActiveXObject("WScript.Shell");
var favfolderName = object.SpecialFolders("Favorites");
if (favString === "") {
GetFavourites(favfolderName);
}
}
}
catch (err) {
alert("Security settings to be modified in your browser ");
}
}
Note that all I changed was the output from an element to an array named favs. I also removed the i variable, because it wasn't used. After running the script, I checked the array in the developer tools console and it contained all my favourites.
If you're getting no output at all, then either fso is null in the Import method or files.AtEnd() always evaluates to false. Since you're focusing on IE here, you might consider placing alert methods in various places with values to debug (such as alert(fso);) throughout your expected code path.

Categories

Resources