JavaScript in an HTML page can send a message to JavaScript in
PDF content by calling the
postMessage()
method
of the DOM object representing the PDF content. For example, consider
the following embedded PDF content:
<object id="PDFObj" data="test.pdf" type="application/pdf" width="100%" height="100%"/>
The following JavaScript code in the containing HTML content
sends a message to the JavaScript in the PDF file:
pdfObject = document.getElementById("PDFObj");
pdfObject.postMessage(["testMsg", "hello"]);
The PDF file can include JavaScript for receiving this message.
You can add JavaScript code to PDF files in some contexts, including
the document-, folder-, page-, field-, and batch-level contexts.
Only the document-level context, which defines scripts that are
evaluated when the PDF document opens, is discussed here.
A PDF file can add a
messageHandler
property
to the
hostContainer
object. The
messageHandler
property
is an object that defines handler functions to respond to messages.
For example, the following code defines the function to handle messages
received by the PDF file from the host container (which is the HTML
content embedding the PDF file):
this.hostContainer.messageHandler = {onMessage: myOnMessage};
function myOnMessage(aMessage)
{
if(aMessage[0] == "testMsg")
{
app.alert("Test message: " + aMessage[1]);
}
else
{
app.alert("Error");
}
}
JavaScript
code in the HTML page can call the
postMessage()
method
of the PDF object contained in the page. Calling this method sends
a message (
"Hello from HTML"
) to the document-level
JavaScript in the PDF file:
<html>
<head>
<title>PDF Test</title>
<script>
function init()
{
pdfObject = document.getElementById("PDFObj");
try {
pdfObject.postMessage(["alert", "Hello from HTML"]);
}
catch (e)
{
alert( "Error: \n name = " + e.name + "\n message = " + e.message );
}
}
</script>
</head>
<body onload='init()'>
<object
id="PDFObj"
data="test.pdf"
type="application/pdf"
width="100%" height="100%"/>
</body>
</html>
For
a more advanced example, and for information on using Acrobat 8
to add JavaScript to a PDF file, see
Cross-scripting PDF content in Adobe AIR
.