Embed PDF in page and print - IE9 issues - javascript

I have some code which dynamically loads a PDF document into a web page by setting a container's innerHTML to the returned string of this function:
function getPdfString(url) {
return '<object data="' + url + '" type="application/pdf" classid="clsid:ca8a9780-280d-11cf-a24d-444553540000" style="width:100%;height:600px"></object>';
}
In IE with the Adobe Reader plugin installed (as determined by the code that detects the Adobe ActiveX at PDFObject), my code inserts this HTML into a hidden container, puts a reference to the object element into el, and then runs this code (Repeater is a custom class):
log("** start repeater **");
var r = _repeater = new Repeater(function() {
try {
var delta = timeInterval();
log("iteration - " + delta + "ms");
el.gotoFirstPage(); //throws exceptions until the PDF is loaded
log("** assuming success, stop **");
r.stop();
r = undefined;
setTimeout(function() {
el.print(); //should succeed, can't tell because it doesn't throw or return anything
}, 100);
} catch(e) { }
}, 0, 100);
This is very convoluted, but necessary because there's no way to tell when the PDF is loaded, nor whether or not el.print() succeeded. It took me a long time to figure out, but it seems to work well in IE7 and IE8. IE9 has been hit and miss, usually working on my local machine (which runs IIS7.5), but sometimes not. IE9 has never worked when the site is running on my test server, which runs IIS6 out of necessity. I don't know if the version of IIS that I am running is causing my issue, but judging from the Fiddler logs, I doubt it.
I have been poring over Fiddler, making small tweaks here and there to see if anything makes a difference. So far, nothing has. The only difference that I can see is the Server header.
I found that the classid attribute is needed by IE7 and IE8; otherwise, they will make multiple requests for the PDF, and often fail to load it. It also significantly improves IE9's caching behavior.
The PDF is slightly different each time it is acquired. I'm not currently saving it to a temporary file or anything, though I could if it is absolutely necessary (so I could re-send the same PDF in a subsequent request).
The response is being gzip encoded, but I have the same problem whether it is enabled or not.
I have noticed that when the problem occurs, terminating AcroRd32.exe sometimes fixes the issue temporarily.
Side note: Firefox and Opera use the same HTML in an in-page popup which embeds the PDF. This works perfectly fine. (The Adobe Reader NPAPI plugin doesn't have a print() method on it that I have been able to find, sadly, so the popup instructs users to click the embedded view's Print button)
Nothing is stopping me from trying other methods of embedding such as an iframe, but I had some weird issues with it when I first tried it (can't remember what they were now, after all this mess).
I think that's everything I know about the problem right now...

This seems to be a problem specifically with Adobe Reader and the IE plugin. I've found a few forum threads that indicate this is a common, reproducible error (http://forums.adobe.com/thread/758489).
The solution seems to be using an iFrame over an <object>/<embed> tag.

Related

Chrome on Android doesn't offer to open PDFs when opened in new tab after a delay

Apologies that this is a long question, I wanted to make sure it was clear what the problem is and, just as importantly, what it isn't - because I know there are a lot of questions that seem related but they don't seem to be about quite the same issue:
The web application we're developing at work needs to open a URL in a new tab when the user presses a particular button, after an API request has completed. The URL in question happens to open a PDF document.
We're aware of the issue with popup blockers, so are opening a blank tab straight away when the button is pressed, then setting the location to the URL a short time later after the API request completes. And this is working fine on desktop browsers as well as on Safari on iPad.
But there is a peculiar problem with Chrome on Android - at least we have observed the problem on Galaxy tablet versions 6 and 7. I'm aware that for some reason Chrome on Android does not have a built-in PDF viewer - however, it seems that accessing the PDF should trigger the OS to ask the user which app they want to use to view the PDF, and we are OK with that. What we do not want - but what is happening at the moment - is the PDF simply getting downloaded in the background, and the user not being given the option of viewing it directly.
From my research on how browsers handle PDFs, it seems this behaviour is dependent on various response headers - notably Content-Type and Content-Disposition. But we are doing this correctly as far as I know - the Content-Type is application/pdf and there is no Content-Disposition header so it should default to "inline", ie opening up to view rather than downloading. And I have tried adjusting the backend to send this header explicitly, both with and without a filename parameter - with no change in observed behaviour.
I strongly suspect this is a bug with Chrome and/or Android, but I cannot find it clearly reported anywhere. The key thing is that there is a delay in setting the URL - because if I put this directly into the console (which I can do when running browserstack from my desktop; not sure if there's any way to input it into a real device directly):
function test1() {
window.open("url/for/my/pdf");
}
this works fine (the device prompts you with a choice of how to open the PDF)
but not with either
function test2() {
const newTab = window.open();
setTimeout(() => {
newTab.location = "url/for/my/pdf";
}, 1000);
}
or even with this, non-asynchronous, version:
function test3() {
const newTab = window.open();
newTab.location = "url/for/my/pdf";
}
Both test2 and test3 above, when called from the console, result in the PDF being downloaded rather than viewed. And this isn't specific to our endpoints - I've tested it with URLs to various random PDF documents I've found online, and the same behaviour occurs.
So my questions are:
is this a known bug with Chrome or Android?
whatever the answer to 1) above, is there any straightforward workaround which will ensure the user is always prompted to open an application to view the PDF, rather than simply downloading it? (Bearing in mind that we can't avoid the delay between opening the tab and setting the location - or at least this is our preferred way.)
Thanks in advance!

Javascript redirect not working in Edge browser when opened with android ActionView intent, but working after manual reload

Situation
In our Android app (Xamarin), we open a web page using an ActionView intent. The code looks like this:
Intent intent = new Intent((string)Intent.ActionView, Android.Net.Uri.Parse(args.url));
intent.AddFlags(ActivityFlags.NewTask);
The opened page at some point does a JS redirect, with a line like this:
window.location = '...';
We tried many different variations of that line, including window.location.href = '...', window.location.assign('...'); and some more. All show the same behavior.
Problem
This has worked fine for years now, in all browsers - but now we ran into a problem, when the browser on the android device is the Edge browser:
When the browser tab is initially opened by the intent, the window.location = '...' line in Javascript is just ignored by the browser. No error message - just ignored.
However, if that same browser tab with exactly the same URL is opened manually (either by reloading or by copying and pasting the URL), the JS redirect is executed just fine.
Question
How do we fix this, how do we make the JS redirect reliably work?
My guess is that we are running into a security feature, which prevents JS redirects in browser tabs that the user has never interacted with.
Is there something (maybe an intent flag?) to circumvent this? We already tried the flag GrantWriteUriPermission, but it did not help.
Possible duplicates
Android Browser Facebook Redirect Does Not Always Trigger Intent for URL :
The proposed situation of setting the URL on a link and faking a click on it did not work.
Microsoft Edge security
Microsoft Edge recently fixed an issue regarding XSS Targeting Non-Script Elements (June 24, 2021).
The vulnerability was found by two researcher when they visited a website in another language via the Microsoft Edge browser and attempted to translate the page. The goal of the recent fix by Microsoft is to avoid vulnerability regarding accessing dynamically to a content from a third party application and specifically in the case of browser redirection. They need to act quickly because the vulnerability is quite huge.
In order to mitigate a large class of potential cross-site scripting issues, the Microsoft Edge Extension system has incorporated the general concept of Content Security Policy (CSP)
Ok, but ... is there any solution?
Maybe you can find a solution to solve your issue here, in particular the part concerning the <button onclick="...">.
Inline code is considered harmful in concept of CSP and microsoft recommend some good practices :
1 - The clickHandler definition must be moved into an external JavaScript
2 - The inline event handler definitions must be rewritten in terms of addEventListener and extracted into your external js file. If you are currently starting your program using code like <body onload="main();">, consider replacing it by hooking into the DOMContentLoaded event of the document, or the load event of the window, depending on your requirements. Use the former, since it generally triggers more quickly.
3 - Function inside onclick call must be rewritten to avoid converting the string of function into JavaScript for running.
The code exemple of the external .js file cited in the documentation look like this :
function awesome() {
// Do something awesome!
}
function totallyAwesome() {
// do something TOTALLY awesome!
}
function awesomeTask() {
awesome();
totallyAwesome();
}
function clickHandler(e) {
setTimeout(awesomeTask, 1000);
}
function main() {
// Initialization work goes here.
}
// Add event listeners once the DOM has fully loaded by listening for the
// `DOMContentLoaded` event on the document, and adding your listeners to
// specific elements when it triggers.
document.addEventListener('DOMContentLoaded', function () {
document.querySelector('button').addEventListener('click',
clickHandler);
main();
});
Hope it's helps

Replacing entire page via AJAX causes Permission Denied error in IE only

I have an AJAX post that retrieves data from the server and either replaces part of the page or in some cases the full page. This is controlled by a javascript fullRefresh parameter. The problem is the refresh code works find in Firefox but causes a Permission Denied error in the bowels of JQuery after it runs in IE although it would appear to actually replace the page contents successfully.
IE version 11.0.9600.16659
JQuery version 1.8.2
Error message
Unhandled exception at line 2843, column 3 in http://localhost:62761/Scripts/jquery-1.8.2.js
0x800a0046 - JavaScript runtime error: Permission denied
My code is
function RefreshScreenContent(formActionUrl, formHTML, fullRefresh) {
fullRefresh = (typeof fullRefresh === "undefined") ? false : fullRefresh;
if (fullRefresh) {
document.write(formHTML);
document.close();
}
else {
$("#content-parent").html(formHTML);
}
}
The partial refreshes work fine but the full refreshes are the problem. I have tried hardcoding the document.write call to write a well formed simple html page rather than formHTML in case that was somehow the problem but even a simple single word page causes the error.
The actual error occurs a some point later with a callback inside JQuery.
The AJAX post to the server is in the same application i.e. is not a cross domain request. I have seen posts online talking aboue cross domain stuff that is not applicable here.
Can anyone tell me why this is happening and how to stop it? Is there an alternative IE way of replacing the page contents?
Your code is fine (at least at first glance). My guess is that you make the call in such a way, that it is interpreted as cross-domain.
I would suggest checking:
http vs https (most common)
the destination port
the root url
maybe the "destination" page makes some requests of its own, check to be on same domain
The reason why IE may be the only one with the problem is that it has higher security demanding by default that other browsers (check advanced security settings - can't remember where they are put in menu) so it interprets requests in a more "paranoid" manor.
I repeat, what I said is just a guess, based on cases I've been put into.
In the end I used the approach here to replace the body tag in the pgae with the one in the markup the AJAX receives back https://stackoverflow.com/a/7839921/463967
I would have preferred to replace all content not just the body but I can always adapt later to include the header etc as body is enough for my uses right now. This works in IE and Firefox.

how can I force IE9 to "see" the most current javascript when using the debugger?

I'm using IE9 to debug a web app. I made some changes to the javascript after loading the page. I'm not able to get IE9 to stop on the new code. The message is "The code in the document is not loaded". I can set breakpoints when I'm not debugging, but they won't be valid when I start debugging. I'm using IE7 Browswer Mode, IE7 Document Mode.
Things I've tried:
close dev tools window, re-open
stop debugging, start debugging
Ctrl R in dev tools window (same as Clear Browser Cache button)
Ctrl R on the IE9 web page
Ctrl F5 on the Ie9 web page
Clear browser cache for this domain
Check (set) Always refresh cache from server
Next thing to try (I guess) would be closing IE completely. Is that the fix for this? If so, yuck. It takes me a couple of minutes to set the page up so doing that after every JS change really stinks. I can use FF4 to develop the JS, but the JS issue I'm seeing is specific to IE7 so I have to do it this way.
>> How can I get IE9 (running in IE7 mode) to reliably debug the most current JS from the server?
This issue wasn't related to caching etc. IE9 was hitting a script error (missing closing paren) in the new code and not allowing breakpoints anywhere in the script. IE seemed very quiet about the script error though. Anyway, fixing the script error fixed the issues with breakpoints / caching.
If you have access to the code:
In you javascript file reference add a query string, something like this:
<script src="Scripts/main.js?v=1" type="text/javascript"></script>
And every time you change in the js file change the v value to something else, like that the browser will feel that this is a new file and will get it.
Add this:
window.applicationCache.addEventListener('updateready', function (e)
{
if (window.applicationCache.status == window.applicationCache.UPDATEREADY)
{
window.applicationCache.swapCache();
if (confirm('A new version of this site is available. Load it?'))
window.location.reload();
}
}, false);
I found this solution somwhere in the Net. Sorry, but I don't remember the author. It works for me when I debug Web App with JavaScript in Visual Studio and use IE.
I found this question based on the "the code in the document is not loaded" error message. I'm not using IE7 document mode or any of that, just IE9.
Like jcollum, my issue wasn't related to caching.
I'm using MVC.Net, and someone had set up a piece of javascript to rely on a string in the ViewBag. I changed a couple things, and that ViewBag string disappeared, so the resulting javascript looked something like this:
if(!()) {
// Some code
}
Javascript died right here, and wouldn't process the rest of the code in the block. This was confusing, as it was still trying to execute javascript in a different set of script tags, but which relied on a variable set in the other block it wouldn't load.
So, basically, a syntax error was introduced via strange means, and the debugger refused to load some of the code which came after it. Another lesson on the dangers of ViewBag.

jQuery $.get() function succeeds with 200 but returns no content in Firefox

I'm writing my first bit of jQuery, and I'm having a problem with jQuery.get(). I'm calling this;
$.get(url, updateList);
where updateList is defined like so;
function updateList(data)
{
if (data)
{
$('#contentlist').html(data);
}
else
{
$('#contentlist').html('<li>Nothing found. Try again</li>');
}
}
The function runs, and updateList is called. It works fine in Internet Explorer. However, in Firefox, the data parameter is always empty. I would expect it to be filled with the content of the webpage I passed in as the URL. Am I using it wrong?
Notes;
in Firebug, I've enabled the Net panel, and I get the request showing up. I get a 200 OK. The Headers tab looks fine, while the Response and HTML panels are both empty.
The page I'm trying to download is a straight HTML page -- there's no problem with server code.
The page with JavaScript is local to my machine; the page I'm downloading is hosted on the Internet.
I've tried checking the URL by copy-pasting it from my page into the browser -- it happily returns content.
The error occurs even in Firefox Safe Mode -- hopefully that rules out rogue addins.
You probably won't be able to do this due to cross-domain security. Internet Explorer will allow you to Ajax remote domain when running from file://, but Firefox and Chrome won't.
Try to put both files on the same server and see if it works (it should).
You'll most likely need to fix your page that you're quering with XHR because it should be returning content. Copy paste the link in the Firebug net tab and make a new tab, and edit that page with your text editor so it spits content back.
Stick alert (or breakpoint in Firebug) and see if the data returned is not an object (or if there is any data). If the former - you may need to drill into the object to get your markup

Categories

Resources