Print styles overriding screen styles after AirPrint in iOS webview
Asked Answered
C

1

6

I am working on a hybrid HTML5/iOS app that uses the Safari Webview. We are using AirPrint to allow the user print the contents of the webview. The problem I am having is that after the print dialog is opened, the print styles are taking affect on the screen, and even after printing is complete or canceled do not go away. This does not happen in our Windows or Android versions of the app, which use CEF and Android System Webview respectively. Print styles in those versions of the application are only applied to the print out, as expected.

Anyone have any experience using AirPrint with Safari Webview that could shed some light on a solution? I have considered just adding/removing the link tag containing the CSS with javascript before and after printing, but that feels hacky, and doesn't answer the curious question of why print styles are being applied to the screen.

Any help appreciated! Sorry there is no real way to attach code to this!

Crean answered 22/1, 2016 at 15:22 Comment(1)
Could you show us a screenshot of the problem. And if you can, provide a screen shot of the code?Adulteress
T
0

Yes, this is indeed a not expected behaviour. However, we can try to solve this using JavaScript.

Theory: When the print is done, let's reload the stylesheets. The browser will paint the page again and hopefully using screen definitions.

Practice: As we don't have a JavaScript callback after printing, you could try reload your stylesheets using the window.onfocus event, as follows:

function updateStylesheets(){
  var links = document.getElementsByTagName("link");
  for (var x in links) {
    var link = links[x];
    if (link.getAttribute("type").indexOf("css") > -1) {
      link.href = link.href + "?id=" + new Date().getMilliseconds();
    }
  }
}

window.onfocus = updateStylesheets;

In detail, it grabs all <link> tags and appends a random number after, forcing a reload on the stylesheets.

Please let me know if that worked, I'd be glad to help.

Tired answered 29/1, 2016 at 1:27 Comment(4)
This definitely sounds like a possible solution. Not in the office today, but will try this out next week and get back to you. Thanks!Crean
Thanks for trying given the little information given, but unfortunately reloading the styles doesn't help, because the problem is that for whatever reason (webkit bug most likely) the webview is triggering the print media query even on screen, and print styles are being applied. Reloading styles did not reset the state to only screen. Can't seem to find any way to affect this besides reloading the webview by setting window.location, which is very clunky UX.Crean
Hi Eric, you can try another thing: if the print css is on a different <link> tag, try removing it, to force webkit render the former stylesheet.Tired
It sounds totally like crap, but it seems you're running out of optionsTired

© 2022 - 2024 — McMap. All rights reserved.