How Can I Tell if My SWF is Embedded in a PDF?

| No Comments

As I’ve mentioned in previous posts, the Flash Player that’s embedded in Acrobat and Reader 9 has built in functions that take advantage of features available only in Acrobat and Reader. That’s great, but what if I want to write my RIA once and have it be “aware” of it’s container whether that’s an HTML page or a PDF. How can I tell if my SWF is embedded in a PDF? Quoting from the Flex 3 Language Reference…

The ExternalInterface class is the External API, an application programming interface that enables straightforward communication between ActionScript and the Flash Player container – for example, an HTML page with JavaScript. Adobe recommends using ExternalInterface for all JavaScript-ActionScript communication.

Let’s say we want to create a Flex application that can save it’s state information when commented on in Acrobat but we want to use the same SWF in a browser. We’d need to detect the container and then branch our code based on the results.

ExternalInterface works exactly the same way when the container is a PDF as it does when the container is an HTML page. Additionally, the JavaScript “eval” function is available in most browsers as well as Acrobat and Reader. The return value of an ExternalInterface.call() method is the response received from the container. So, if we call “eval” and pass some more JavaScript as the parameter, the return value will be the result of the JavaScript we passed.

All we need now are the right JavaScript calls to identify an HTML page vs a PDF. Most browsers support “navigator.userAgent” which tells you a lot about the browser and, if you are running in a PDF, “app.viewerType” will tell you and if that PDF is in Acrobat or Reader.

Basically, if app.viewerType returns null, then we know we’re in the browser. If it returns "Reader", "Exchange", or "Exchange-Pro", then you know you’re in a PDF.

In the examples below, the same SWF file is playing in the browser’s Flash Player and in also in a PDF embedded on this page.

The SWF above is playing in your browser.
The one below is playing inside a PDF document.

The Flex Project for this example is below.

Example Source Code

Previous Posts on this topic:
Saving the State of SWF Content in Acrobat 9
Enabling Commenting of SWF content in Acrobat 9