Run JavaScript in PDF When Document Opens - javascript

Using Adobe Acrobat Pro DC, I need certain form fields to clear their values when the document opens. Here's one line I've placed in Tools > JavaScript > Document JavaScripts:
getField("Patient").value = "";
However, that doesn't run when the PDF is opened. (It works when called from a Document Action.)
Thanks

The exact moment when a document-level script is executed is not known, and that means that a field may not yet have been created when the script runs.
In my experience, when it comes to set field values when the document opens, it is much safer to use the pageOpen event of the page at which the document opens.
Note: when you have a multi-page document, you will need to make sure that this piece of code gets executed only once; this is done in a way like this:
In a document-level script define:
var loaded = 0 ;
In the pageOpen script have this construct:
if (loaded < 1) {
// execute code when document opens
loaded++ ;
} else {
// execute code when returning to the page
}
And that takes care of the situation.

Related

JavaScript onclick event works only as double-click

I'm writing because I need to solve this problem. Until recently, the code was working just fine and I've been using it for quite a long time, but yesterday, when I was testing the page, everything changed.
The idea is click on an image with an anchor tag that is going to redirect the user to another page and in doing so, a confirm dialog box should pop up to ask the person whether they want that. I haven't changed anything in the code, so I'm not getting what's happening. Here's the code:
// **JavaScript**
function confPopUp() {
for (var i = 0; i < 6; i++) {
document.getElementsByClassName("redPic")[i].onclick = redConf;
}
}
function redConf() {
var conf = confirm(
"You're about to be redirected to our social media page. Do you accept?"
);
if (conf) {
return true;
} else {
return false;
}
}
window.onclick = confPopUp;
<!-- **HTML** //THERE ARE 5 MORE ELEMENTS WITH THE CLASS NAME "redPic". -->
<img class="redPic" src="images/instagramLogo.png" alt="Instagram Logo">
The problem is that I'm testing it, right now, and it's not working properly, a the day before yesterday it was working fine, only one click and now, it's working as double-click.
I'd appreciate your help, thanks.
When the page first loads, you're setting a single event handler:
window.onclick=confPopUp;
Later, when there's a click anywhere in the window, that runs your confPopUp function, which hooks up the click handlers on the .redPic elements.
Later, if you click a .redPic element, your redConf function runs.
If you want the .redPic elements to have their handlers hooked up on page load, call confPopUp instead of making it a click handler. Change:
window.onclick=confPopUp;
to
confPopUp();
Be sure this code is running after the .redPic elements exist. There are several ways to do that, pick the one that suits your target browsers and preference:
Put the code in a script tag at the end of the document, just before the closing </body> tag. This works with all browsers, no matter how old.
In even vaguely-modern browsers, call confPopUp from a DOMContentLoaded event handler:
document.addEventListener("DOMContentLoaded", confPopUp);
In modern browsers, add a defer attribute to your script tag.
In modern browsers, add type="module" to your script tag to make your script a module. That defers it just like defer does, and puts it in strict mode (which is a good idea), and put the code in it in module scope rather than global scope (which is really crowded).
So why did it seem to work yesterday? Presumably, because you were clicking the window without realizing it, triggering that initial event handler that hooked up the .redPic elements. Today it just happened that you didn't click the window before trying to click a .redPic element, so you discovered this problem. The problem's been there all along.

Javascript executes first then text in body loads later

Why in my browser when i run this first my java script file runs then it loads the text inside body , but when i ran this in stackoverflow javascript snippet tool it runs fine.
var name= prompt("enter your name");
var age= prompt("enter your age");
var pet_name= prompt("enter your fav pets name");
alert("hi "+name+" your age is "+age+"and you love"+pet_name);
console.log("hi "+name+" your age is "+age+"and you love"+pet_name);
<!DOCTYPE html>
<html>
<head>
<title>testing javascript</title>
</head>
<body>
<h4>Testing of my first java script</h4>
<script type="text/javascript" src="test_1.js"></script>
</body>
</html>
I believe this is because alert, confirm and prompt are all 'blocking' functions and they are being called at the same time the rendering is occuring, try putting the code in a setTimeout or document ready:
document.addEventListener("DOMContentLoaded", function(event) {
// your code
});
or
var delayedScript = function() {
// your code
}
setTimeout(delayedScript, 500);
https://developer.mozilla.org/en-US/docs/Web/API/Window/prompt#Notes
Dialog boxes are modal windows; they prevent the user from accessing the rest of the program's interface until the dialog box is closed
It does appear that your code is executing just fine, so the only conclusion I can think of is that the script tag is not correctly implemented.
Verify that it's name is indeed 'test_1.js', and that it is located in the same location as the file your html is located in.
If it is not, you can use a relative path.
A few other points:
The type javascript is redundant as Javascript is the default scripting language of the web.
You are missing spaces after the age variable and after the 'love' string.
I hope this helps :)
The behavior is browser specific. A particular browser may wait until the end of a page's input stream has been reached before rendering the page: perhaps a positioned element located near the end of the file might still need to be rendered at the top of the page.
Now popup dialogs in javascript, like alert, confirm and prompt have a synchronous blocking action on script, which can pause HTML parsing until they have been responded to. So browsers such as Chrome, which don't render until page input has been completed, won't show text from above the script block until the prompts have been answered or dismissed.
Browsers such as Firefox which incrementally render pages may show text from above the script block.
The code snippet facility in SO works differently. It processes content from the HTML box, puts it into the output pane, and then processes content from the script panel. So the HTML content appears first.
Snippet code that requires waiting for a window "load" or document "DOMContentLoaded" event is not tested properly using the snippet facility.
The general solution to using popup dialogs after page rendering is (as suggested already) to defer processing the relevant code until after the "DOMContentLoaded" event has been fired on the document or "load" on the window.

Use javascript (and jQuery and other libs) from parent document on iframe with several sources

good day all.
I'm working on a project in which there is an application that has one of its view implemented with an iframe, the iframe src is changed when the user clicks on some of the "parent" document. So basically there is always the same container, but the contents of the iframe will change according to the user choices.
let's say that there will be:
parent.html (which will have all the js logic)
child1.html
child2.html
...
each "child" page will be an html page with no (or very little) javascript. What I want to obtain is that when the user arrive on the child1.html, only the code that is global to every child is execute and of course also the code related to that page.
Let's say that on the child1.html there must be executed a couple of ajax calls, then some js to handle tables, and things like that. while on the child2.html there will be some forms whith their own validations, and another ajax call to send the forms (displayed on the child1.html).
There will be a big js library on parent.html that will contain the js code of every child page, so what I'd like to have is a way to "know" in which page I am and execute only the portion of code that is related to that page.
the structure should be something like:
var myGlobalObject = {username:undefined,foo:1}
if(childpage1.html){
if (myGlobalObject.username == undefined){
$.ajax(retrieve username);
$("#someTableIniFrame",iframeContext).doSomething();
}
}
if(childpage2.html){
$("body",iframeContext2).on("submit","#someFormOnChild2", function(){
//do something
});
}
and/or something on childpages that could execute only its code... like:
document.addEventListener("DOMContentLoaded", function(event) {
//execute only my part of the global js!
});
I hope to have been clear on what I'd like to obtain:
a parent page, with all the js used in childs, executed on demand OR with the capability to understand in which page we are.
several child page without or with a very little js.
Just for information, the iframe src will be changed by js on the parent page, by destroying the previous one and adding a new iframe with the new source.
If you want to keep all the Javascript in the parent page then you just really need a way to map the child pages to any code you wish to execute. This is a long way around doing something, but without further context it's difficult to suggest a more appropriate solution.
With that in mind, here's how I'd approach your problem.
First of all, I'd create an array of objects that defines what script to run for each child page...
var childScripts = [{
"src": "childpage1.html",
"init": function() {
// what to do when childpage1 is loaded
}
},
{
"src": "childpage2.html",
"init": function() {
// what to do when childpage2 is loaded
}
}];
Don't destroy and recreate the iFrame every time you want to load a new page, or (if you really have to), assign an event handler to the load event every time. You only have to do this once if you never destroy the iFrame...
$("#iframeId").on("load", function() {
var scriptInfo = childScripts.filter(function(childInfo) {
return window.location.href.slice(-childInfo.src.length) === childInfo.src;
});
for (var i in scriptInfo) {
scriptInfo[i].init();
}
});
Obviously replace the selector #iframeId with something that will find your iframe.
In short, you create an array that holds each child page filename (prefix with / so you don't run scripts on pages that end with the same thing, but aren't the same page), and a function that you want to execute when that page loads. You then parse that array each time the iframe is loaded and execute all associated functions. Realistically you'll only have 1 init function per child page, but that code will handle multiple instances.

Stop jQuery evaluating scripts that have already been executed

I have a history API script that loads new page content without the need for a page refresh. I have come into a problem with inline scripts, where the scripts are evaluated by jQuery even if they have been done so previously. So for example, if someone re-visits a page with an inline script that script will be executed each time they re-visit. This causes problems as say if a DOM element is added in a script than that element will be added several times if they have visited that page several times.
For reasons I won't go into I cannot put these inline scripts into an external file and load them that way.
Here's the coded that deals with the scripts;
dom.filter('script').each(function(){//function to allow inline javascript, has to be after page fadeIn incase scripts reference page DOM
$.globalEval(this.text || this.textContent || this.innerHTML || '');
var script_src = ($(this).attr('src'));
if (script_src === 'AJAX/request_feed.js' || script_src === 'js/profile.js'){
$(window).unbind('scroll');
$.getScript(script_src);
}
});
Should you require any more parts from the whole history script just ask. i don't think they're required though.
Note: The if clause is there for a scroll loader i have. I have two scroll_loaders so the scroll event needs to be unbinded and binded each time. No need to worry about that though.
You could store your executed scripts in a cookie, then check the cookie before executing. One way or another, you'll need some way of keeping track of what has been executed and what hasn't been.
Alternate Suggestion
You could tweak your scripts to be self regulating:
myscript.js:
(function(){
if ($(this).parent().script_registry.inArray('myscript')) return false;
$(this).parent().script_registry.push('myscript'); // Register this script as launched
alert('Do stuff..');
});
Note: The above code may not be 100% syntactically correct.

jQuery code repeating problem

I have a piece of code in jQuery that I use to get the contents of an iFrame after you click a link and once the content is completed loading. It works, but I have a problem with it repeating - at least I think that is what it is doing, but I can't figure out why or how.
jQuery JS:
$(".pageSaveButton").bind("click",function(){
var theID = $(this).attr("rel");
$("#fileuploadframe").load(function(){
var response = $("#fileuploadframe").contents().find("html").html();
$.post("siteCreator.script.php",
{action:"savePage",html:response, id: theID},
function(data){
alert(data);
});
});
});
HTML Links ( one of many ):
<a href="templates/1000/files/index.php?pg=0&preview=false"
target="fileuploadframe" class="pageSaveButton" rel="0">Home</a>
So when you click the link, the page that is linked to is opened into the iframe, then the JS fires and waits for the content to finish loading and then grabs the iframe's content and sends it to a PHP script to save to a file. I have a problem where when you click multiple links in a row to save multiple files, the content of all the previous files are overwritten with the current file you have clicked on. I have checked my PHP and am pretty positive the fault is with the JS.
I have noticed that - since I have the PHP's return value alerted - that I get multiple alert boxes. If it is the first link you have clicked on since the main page loaded - then it is fine, but when you click on a second link you get the alert for each of the previous pages you clicked on in addition to the expected alert for the current page.
I hope I have explained well, please let me know if I need to explain better - I really need help resolving this. :) (and if you think the php script is relevant, I can post it - but it only prints out the $_POST variables to let me know what page info is being sent for debugging purposes.)
Thanks ahead of time,
Key
From jQuery .load() documentation I think you need to change your script to:
$(".pageSaveButton").bind("click",function(){
var theID = $(this).attr("rel");
var lnk = $(this).attr("href");//LINK TO LOAD
$("#fileuploadframe").load(lnk,
function(){
//EXECUTE AFTER LOAD IS COMPLETE
var response = $("#fileuploadframe").contents().find("html").html();
$.post("siteCreator.script.php",
{
action:"savePage",
html:response,
id: theID
},
function(data){alert(data);}
);
});
});
As for the multiple responses, you can use something like blockui to disable any further clicks till the .post call returns.
This is because the line
$("#fileuploadframe").load(function(){
Gets executed every time you press a link. Only add the loadhandler to the iframe on document.ready.
If a user has the ability via your UI to click multiple links that trigger this function, then you are going to run into this problem no matter what since you use the single iframe. I would suggest creating an iframe per save process, that why the rendering of one will not affect the other.

Categories

Resources