How do you debug printable CSS? - css

I use Firebug and IE Developer Toolbar all the time to debug tricky CSS problems. But occasionally, a tricky bug comes up that only appears when you go to print the page.
What techniques/tools do you use to diagnose problems like this? Is there a way to get more use out of traditional CSS debugging tools in print view?
Updated: I already use a PDF printer to avoid wasting paper; my problem is that I can't right-click on the printed DOM. Some of the other answers below are quite helpful, thanks. :-)

Just found a comment by lee-penkman about a new feature in Firefox here: Press Shift-F2 in Firefox to open the browser console (not the javascript console), then enter media emulate print. Works absolutely great!
Update Sept. 2018: Starting with Firefox 62, the developer console has disappeared. There doesn't seem to be a way to activate print style emulation now.
Update Nov. 2019: It seems that in Firefox 69, there is again a new button for print style emulation. See the other answer on this page: https://stackoverflow.com/a/58015662/195476

In Chrome 51:
Open devtools (CTRL + F12 or CTRL + SHIFT + I) and click on the ... menu, click More Tools > Rendering settings to open the Rendering tab of the developer console (alternatively, if the console is open just navigate to this tab).
In that tab, select and check the box for Emulate Media: print.

I use the WebDeveloper plugin and the CSS --> Display CSS by Media Type --> Print to view the CSS as it would when printed. Firebug's inspection utilities work with the CSS as filtered by the plugin.

In Firefox 69, I found a button to simulate print media. Just open the Developer Tools (F12) and click on Inspector. The toggle button is the leftmost icon that's in the highlighted section in the screenshot below, the one that looks like a sheet of paper.

I use Firefox and the developer toolbar.
I use the real time css edit tool in the task bar, it's pretty usefull to modify your css on the fly on see the results in real time.
I also use the outline feature, which the div and stuff like that on mouse over, on your website. Really helpful to find div.
For the print problem, go to CSS -> Display CSS style by media -> print
There are a lot of other tool available in this one, I probably use about 10% of it.
Try maybe you find something usefull.

In chrome developer tools (F12 \ Ctrl(cmd on mac) + Shift + C):
In the emulation tab (From Chrome 32 onward IMHO), there is a tab for 'Media'.
There you can check the media emulation checkbox and select the media you would like to emulate ('print', 'screen' etc.)

How about just listing your print CSS last, and removing the "print" condition from your CSS link or import statement? Then you're debugging the print CSS in the browser window.

I use the Adobe PDF virtual printer, because it's the closest thing to a real printer you'd get, without wasting ink and paper.
Anyway, it's recommended to have a separate CSS for prints, with much simpler graphics and less of the images you use just for design purposes.

I always used web developer toolbar (as described in the other answers), but Firebug seems to miss some styles from time to time. So I added a Bookmark to my browser and added the following Javascript as URL of the bookmark. Now I can simply switch to print style by clicking the bookmark:
javascript:(function(){var%20h,a,f;a=document.getElementsByTagName('link');for(h=0;h<a.length;h++){f=a[h];if(f.rel.toLowerCase().match(/stylesheet/)&&f.href&&(f.media=='print'||f.media=='screen')){var%20g=f.href.replace(/(&|%5C?)forceReload=\d+/,'');if(f.media.toLowerCase().match(/screen/))f.media="dontshow";if(f.media.toLowerCase().match(/print/))f.media="all";f.href=g+(g.match(/\?/)?'&':'?')+'forceReload='+(new%20Date().valueOf());}}})()
The code above finds all stylesheet links, tests if it is media=print and if so it changes it to media=all (and hides all media=screen by replacing it with media=dontshow) and reloads the stylesheets by adding a time token to the URL. The basic reload script is from someone else, I added media part.
This works great for me!
This would be the more readable version of the JavaScript URL above for explanation:
javascript: (function() {
var h, a, f;
a = document.getElementsByTagName('link');
for (h = 0; h < a.length; h++) {
f = a[h];
if (f.rel.toLowerCase().match(/stylesheet/) && f.href && (f.media == 'print' || f.media == 'screen')) {
var g = f.href.replace(/(&|\?)forceReload=\d /, '');
if (f.media.toLowerCase().match(/screen/)) f.media = "dontshow";
if (f.media.toLowerCase().match(/print/)) f.media = "all";
f.href = g(g.match(/\?/) ? '&' : '?')
'forceReload=' (new Date().valueOf());
}
}
})()

Print to Microsoft XPS Document Writer if you don't want to pay money. Or use SnagIt if you've got the funds (free trial on site).

Related

In wordpress Chrome & Firefox element Inspector show View source does not, which is correct

I am trying to debug a Wordpress issue where a is being auto inserted before the end of the <script> tag, hence breaking the javascript.
If I view the element with the inspector, I can see a as shown below:
However if I viewsource, or download the html page and look at it, there is no :
});
});
setTheRepeaterButton();
});
</script></p>
At first i thought it was a chrome bug, but I get the exact same behaviour in firefox.
I would think there is no , however the script is broken which implies there is one. Which is correct, the inspector or the page source?
It looks like there is a hidden/invisible character before the final } in the script. Depending on your code editor, you can toggle a setting to view hidden characters or add a plugin (e.g. nbsp-vscode for VS Code).
Or the easiest solution is to delete the space between that } and the preceding ; and redo the code formatting.

Print existing pdf file directly to client default printer [duplicate]

A coworker and I were having a discussion about what is and isn't possible within the browser.
Then a question came up that neither of us could answer with certainty.
Can you create a webpage such that when you navigate to it, it engages the client-side printer and attempts to print a document. For instance, whenever you visit my personal website, you'll be treated to a print out of a picture of me, smiling.
Now, this is a hideous idea. I'm aware. But the discussion intrigued me as to if it could be done, and how. My friend insisted that the best you could do was pop up the print dialog for the user, they would have to click print themselves.
Would it be possible to bypass this step? Or just some fancy script to move the mouse over the print button and click on it? Or use an activeX control to interface with a Printer API directly?
You have to prompt the user to print the current page, there's no way to bypass this step (possibly in activeX for IE). That said, there's two different ways you could prompt the user to print images of you smiling when the page is loaded.
Here's how to do it in JavaScript.
window.onload = function() {
var img = window.open("me-smiling.png");
img.print();
}
And here's how to do it in css/javascript/html (assuming your picture has the id 'me-smiling'):
CSS:
#media print {
* {
display:none;
}
img#me-smiling {
display:block;
}
}
Javascript:
window.onload = function() { window.print() }
The only solution to avoid print dialog that I found was creating a variable on Mozilla Firefox to set auto-print. Maybe is not the best solution if you need to use other browser, but in my case, I only need to print a report automatically and it works:
1- Open Firefox and type "about:config" in the address bar
2- Right click on any preference and select "New" > "Boolean"
3- Add a variable called "print.always_print_silent" with "true" value
4- Restart Firefox.
Hope help you!
AttendStar created a free add-on that suppresses the dialog box and removes all headers and footers for most versions of Firefox.
https://addons.mozilla.org/en-US/firefox/addon/attendprint/
With that feature on you can use $('img').jqprint(); and jqprint for jquery will only print that image automatically called from your web application.
As far as I know, there is no way to print a document directly, without some client intervention, like setting browser flags.
In our current project we need to print directly to the default printer, but at least with Chrome you can do it easily with additional startup arguments.
To print directly to the OS default printer you can use:
"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" --user-data-dir=c:\tmp --kiosk-printing http://www.contoso.com
Another option, which may also be useful, is tos use the native print dialog instead of chromes print preview.
"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" --user-data-dir=c:\tmp --disable-print-preview http://www.contoso.com
Note, that window.print() and/or Ctrl-P behave accordingly the mentioned settings.
I know, that this does not exactly answers the OPs question, but I think it somewhat related, and for web based enterprise applications this is a quite common use case. Maybe someone find it useful.
For Firefox I recommend Seamless Print Addon
You can't bypass the print dialog, as far as I know. That would be a pretty obvious security flaw if the browser allowed that. But you can bring up the print dialog with "window.print()".
I think at best you would need an ActiveX component using base windows API to obtain a device context for the default printer and try and print an embedded image using assumed values for the printer settings.
To print to the default printer automatically without seeing a print dialog prompt, I've shared some code in the following question that works in IE7, IE8 and IE9:
Bypass Printdialog in IE9
From lot of search from last few days,
I've found a best possible solution.
Till date Chrome do not support direct printing from javascript.
It has launched USB and serial API which might help.
But currently I'm using a JavaApplet solution which is open source.
https://github.com/qzind/qz-print - build
While I'm getting error in building it. I preferred a Prebuilt - QZ Print Plugin 1.9.3
desktop app, which works great.
Download it from here: https://qz.io/download/
Code Example:
/***************************************************************************
* Prototype function for printing an HTML screenshot of the existing page
* Usage: (identical to appendImage(), but uses html2canvas for png rendering)
* qz.setPaperSize("8.5in", "11.0in"); // US Letter
* qz.setAutoSize(true);
* qz.appendImage($("canvas")[0].toDataURL('image/png'));
***************************************************************************/
function printHTML5Page() {
$("#qz-status").html2canvas({
canvas: hidden_screenshot,
onrendered: function() {
if (notReady()) { return; }
// Optional, set up custom page size. These only work for PostScript printing.
// setPaperSize() must be called before setAutoSize(), setOrientation(), etc.
qz.setPaperSize("8.5in", "11.0in"); // US Letter
qz.setAutoSize(true);
qz.appendImage($("canvas")[0].toDataURL('image/png'));
//qz.setCopies(3);
qz.setCopies(parseInt(document.getElementById("copies").value));
// Automatically gets called when "qz.appendFile()" is finished.
window['qzDoneAppending'] = function() {
// Tell the applet to print.
qz.printPS();
// Remove reference to this function
window['qzDoneAppending'] = null;
};
}
});
}
Complete example can be found here:
https://gist.github.com/bkrajendra/c80de17b627e59287f7c
This is the best solution that I have found for firefox:
There is this awesome add-on Seamless Print.
It works like charm.

Inject CSS with chrome developer tool?

Where can I add CSS to the page I'm viewing? I don't want to add style to one element directly, I want to add a 'document' to a page to debug changes before editing the site's style.css.
Note, there are lots of questions here about 'injecting CSS from a chrome extension', but specifically I want to do it via the 'Chrome Developer Tools' thingy.
I'm not sure if it works, but you'd have to try.
Pressing F12/ (Cmd + opt + I on Mac) to open up the Developer Console and go to the Console tab.
Copy paste the following code (edit the path):
$(document.head).append('<link rel="stylesheet" href="path_to_my_css">');
Alternatively, you could edit one property so the inspector-stylesheet.css is created by Chrome, and copy past your CSS source there.
There are multiple ways to do that, and they are also very easy.
First way, inspector-stylesheet:
Open Inspect Element (F12 Or Ctrl+ Shift+I)
Go to Elements tab (Ctrl+ Shift+ P and type show elements), if you are not already there, see the Styles tab, now see on right corner, there would be a + icon, click it (or long press that icon if it doesn't automatically add inspector-stylesheet), it will add selector of currently highlighted element, just next to the selector, there will a link/button inspector-stylesheet, click it, it will take you a window, where you can add styles.
Second way, Edit as HTML
Open Inspect Element (F12 Or Ctrl+ Shift+I)
Go to element panel (Ctrl+ Shift+ p and type show element panel).
Scroll to the head element right click on the element and choose Edit as HTML, go to the bottom of that element (Ctrl+ End), add your <style></style> element there add your style in that element, and hit Ctrl+ Enter.
Third way, Snippet:
Open Inspect Element (F12 Or Ctrl+ Shift+I)
Go to the Source tab, go to the Snippets tab, click on the + New snippet, name it whatever you want, and add this:
Create new snippet Ctrl+ Shift+ P type Create new snippet hit Enter , rename the snippet if you want to, and add this (edit the style) :
(function(){
let style = `<style>
/*change your style here*/
body{
display:none;
}
</style>`;
document.head.insertAdjacentHTML("beforeend", style);
})();
Save it, run it (Ctrl+Enter).
You can also run the snippets by doing this: Ctrl+ p type ! it will show your saved snippets, choose the one you want to run.
To edit or see your snippets, Ctrl+ Shift+ P type show snippets.
In FireFox it's even easier:
Open Inspect Element (F12)
Go to Style Editor, click the + icon and you will be able to edit the style; You can also, import styles, just by clicking the icon next to the +.
To begin with, this is one reason why I use Firefox for teaching and my own development work. The answer is built in.
As a variation to the above answers, using modern JavaScript, you can add a hard-coded style as follows:
document.head.insertAdjacentHTML('beforeend','<style> … </style>');
or you can add an external style sheet as follows:
document.head.insertAdjacentHTML('beforeend','<link rel="stylesheet" href="…">');
The beforeend argument is to help the injected CSS to override previously loaded styles.
If you’re going to do this repeatedly, you can then add it as a bookmarklet, using something like Bookmarklet Crunchinator.
The technique is similar to one I teach in a JavaScript class, where I use afterbegin to inject some default CSS, but allow user style sheets to override the defaults.
Why not a kind of simple framework agnostic one-liner like this?
document.body.appendChild(function() {var el = document.createElement('link'); el.setAttribute('rel', 'stylesheet'); el.setAttribute('href', 'http://domain/print.css'); return el;}())
Seems to work like a charm...
Since 2018 in Chrome (65) the browser's integrated DevTools has a feature called Local Overrides 1. As such, there is no need for an add-on or extension like StyleBot, Stylish or Greasemonkey.
Local Overrides allow rewrites of CSS, JS and DOM on any live site. Changes are saved in a local folder and they override the contents of the live environment.
This can be accessed under Developer Tools > Sources >> Overrides
This allows you to select a custom local folder that will contain CSS and JS that will override the current website's own CSS and JS.
This should work (paste into console, edit arguments in the last line as needed):
(function(i,n,j,e,c,t,css){
css=i.createElement(n);t=i.getElementsByTagName(c)[0];css.href=j;css.rel=e;
t.insertAdjacentElement('beforeend',css);})
(document,'link','//fonts.googleapis.com/css?family=Roboto','stylesheet','head');
This will insert a <link>
with an href //fonts.googleapis.com/css?family=Roboto
before the closing </head>
If there's no head tag in the document you're trying to add a css file to, try body as the last argument:
(document,'link','//fonts.googleapis.com/css?family=Roboto','stylesheet','body');
You can inject CSS using snippets in Chrome Devtools. Save and execute the snippet and then invoke it in the console or in another snippet:
function insertCss(code) {
var style = document.createElement('style');
style.type = 'text/css';
if (style.styleSheet) { // IE
style.styleSheet.cssText = code;
} else { // Other browsers
style.innerHTML = code;
}
document.getElementsByTagName("head")[0].appendChild( style );
}
// run the snippet as follows:
insertCss('span { color: red !important; }');
Go to the sources tab in dev tools and right click in the left column, then add folder to workspace and use file explorer to select the folder that contains your css file. You will have to allow to make changes, once you do this you will see your folder in the sources tree(MAKE SURE YOU SELECT FILESYSTEM TAB UNDER SOURCES TAB), open your folder find the file and right click on the your css file and select map to network resource. Once you map the file you can open and see it in the workspace and from that file any change made will affect the page styles. So basically your styles will over ride the served styles.
Is this what you're after?: "How to Edit Source Files Directly in Chrome" http://www.sitepoint.com/edit-source-files-in-chrome/
From that article:
Step 1: Launch Developer Tools. Go to View -> Developer -> Developer Tools. Navigate to "Sources"
Step 2: Click the Filesystem tab, then click + Add folder to workspace. You’ll be prompted to locate your work folder and Chrome will ask you to confirm that you Allow access.
Step 3: Edit and Save Your Code and refresh the browser to see your changes

Chrome developer tools - any way to see what CSS is used by the current page?

Using Google's Chrome Developer Tools, I sometimes run audits on my code to see how it is coming together. One of the suggestions those tools always make is "Removed Unused CSS Rules". Clicking on the arrow then shows a usually huge list of the CSS rules that are not being used by the current page.
Is there a way to see a list of what CSS rules ARE being used by the current page?
I know this may be a tad late but in case someone else stumbles across this like I did and is also curious I found the Dust-Me Selectors add-on for firefox will tell you both the used and unused selectors on the page for each stylesheet used.
Hope this Helps
Press CTRL-SHIFT-J to access Chrome's dev tools. There you can choose resources tab, choose to enable them on the left and refresh the page if necessary. It will show all loaded files, including stylesheets.
The developer tools are open source so you can create a patch.
http://dev.bootstraponline.com/2011/11/automatically-remove-unused-css-rules.html
snipp
//=== modified file 'AuditRules.js'
if (!testedSelectors[rule.selectorText] || foundSelectors[rule.selectorText])
{
usedCss += "\n" + rule.selectorText + " {" + rule.style.cssText + "}\n";
continue;
}
//...
// Save only used css rules.
InspectorFrontendHost.saveAs("used.css", usedCss);

Export CSS changes from inspector (webkit, firebug, etc)

When I'm working with CSS, I'll often test in a browser - say, Chrome - right click an element, click Inspect Element, and edit the CSS right there. The use of arrow keys to change things like margin and padding makes lining things up super easy.
It's not too hard to then take those changes and apply them to the CSS file, but it would be cool if I could just right click the selector in the inspector and select "export" or "copy", and have the contents available in my clipboard.
Does something like this exist?
I have found the answer to this, at least as of Chrome v14.
While in the Elements section, just click on the "filename:linenumber" link next to the CSS rules. The CSS file that shows up will contain all of the modifications.
This place exactly:
In Chrome, you can right-click a CSS file in the Sources tab and click "Local Modifications"
This shows you all of your local changes. Each revision is timestamped and you can rollback to any previous revision.
See the Live Editing and Revision History section of this tutorial.
Firediff is a Firebug add-on that tracks changes done in Firebug. It logs everything you'll do in the HTML pane (great) but also your brief use of the Web Developer Toolbar extension (not so great), say Shift-Ctrl-F to obtain a font-size information in px.
I have seen a Firebug extension in Chrome but didn't test it, I use Firediff with Firefox.
In Chrome there is also the Changes tab in the console drawer that displays all the modifications of CSS. It's not an export, but at least it is very convenient to quickly grasp what has changed.
I built a Chrome extension that does exactly this.
It's called StyleURL - it takes whatever CSS changes you made in Chrome Inspector and outputs valid CSS as the diff: https://chrome.google.com/webstore/detail/styleurl/emplcligcppnlalfjknjbanolhlnkmgp
Here's an example where I added "padding-bottom: 50px" to this page:
It's open-source and on GitHub too: https://github.com/Jarred-Sumner/styleurl-extension
Both Firefox and Chrome support this feature now, but worth to note that in some platforms if not all Chrome does not show it by default, you need to enable the "Changes" view to see it (in my Kubuntu Linux 20.04 it wasn't by default), here is how you can enable it: go to the "Customize and Control DevTools" button in the Developer Tools bar > "More tools" > "Changes", then the tab will appear at the button:
In Firefox there is no need to enable it, but if you come from the Chrom* world may be hard to find it. Just check the last section in the right at the "Inspector" tab:
I've suggested this product on SO before (I'm not affiliated with them in any way).
http://www.skybound.ca/
Excellent product. Sounds like exactly what you're looking for and much more.
EDIT: Several other answers here have mentioned Google Chrome's ability to link to your local files (which is very very cool). Check out the other answers!
If you edit external CSS, then you can drag its latest revision out of the Resources panel into any text editor that supports DnD (see http://www.webkit.org/blog/1463/web-inspector-styles-enhanced/, the "Persisting Changes" section for more detail.) You can also revert your CSS changes to any earlier version of the stylesheet resource (in the right-click popup menu of any stylesheet revision.)
As mentioned by cloudworks, the answer to this has changed. This can now be accomplished rather well by the Chrome DevTools Autosave extension. This tool tracks CSS and JavaScript changes made within the Chrome Developer Tools console, and saves them back to local files. For instructions to install and setup the extension, please refer to the guide written by #addyosmani on his blog, here.
There is also a handy screencast which details the extension rather well.
With Workspaces you can have your CSS saved as you type them in your inspector (in Chrome). The problem is that every change is automatically saved and there's no way to disable this feature, as pointed in http://www.html5rocks.com/en/tutorials/developertools/revolutions2013/ and Disable automatic saving of CSS changes in Chrome Developer Tools.
My in-beta-soon product LIVEditor does this exactly.
To let you understand it easily, you can think of Firebug's inspector is embedded into your text editor.
That way you don't have to make the changes manually again in your code editor after you tweaking it using Firebug or Webkit's developer tools.
If you're using the Firefox stock dev tools you can edit the css directly in the tools dialog - click the CSS viewport button (that's the button at the top with the {} symbol) and edit your css directly. It will update in realtime in the browser and when you're done just copy-paste it directly into your css file. Nice!
To add an answer for Safari specifically — it's kind of possible.
When you edit CSS in the Styles section in the Inspector for an existing CSS file, you can hit Cmd-S to re-save the entire file with the changes. However, if you're using a meta language like Sass / preprocessor / generating your CSS with bundling etc, I don't think this really solves that problem, though it may be possible with CSS source maps.
When you edit CSS at the top of the Styles section, under Style Attribute to add inline styles (not tied to an existing CSS file), it doesn't seem possible to easily export all of those changes. For now, I'm just copying and pasting the overrides manually for each element.
The official Apple docs are a little dated but found here: Web Inspector Tutorial - Editing Code to Change Your Webpage.
In Chrome, in the css inspector you can click and hold the + button, then choose to add your changes to the inspector-stylesheet. It's not as convenient as directly editing in your css-selectors, but what you write will all be in inspector-stylesheet.css

Resources