Inserting CSS with a Firefox Extension - javascript

I'm building a Firefox extension that adds HTML elements to certain pages of a website. I want to have it insert a custom CSS file to style those elements. It works if I insert tags with the CSS right on the page, but that's a less than ideal solution.
Is there anyway to get it to load and parse a CSS file, as if I used the tag in the header, or am I stuck inlining it somehow?

chrome:// won't work because the page you are inserting into isn't allowed to access files outside of it's domain (including chrome URIs). This is true even you are the one inserting the link, because the link is still executed in the context of the target page. Instead you have two options:
You can define a resource protocol alias in your manifest and then use a resource URI to access the CSS. For example, the following chrome.manifest will allow you to insert the css as resource://myextresource/myfile.css:
content myext content/
resource myextresource content/css/
See MDN Chrome registration for more info. Also see How can a Firefox extension inject a local css file into a webpage? for a similar question.
Or, you can add the CSS as a USER_SHEET using the following. This will make your CSS available across all pages, so be sure you use very unique selectors. One caveat with this approach is that the page CSS has precedence over user sheets. You can use !important to override that, but the page CSS can still trump you if it uses !important as well.
var sss = Components.classes["#mozilla.org/content/style-sheet-service;1"]
.getService(Components.interfaces.nsIStyleSheetService);
var ios = Components.classes["#mozilla.org/network/io-service;1"]
.getService(Components.interfaces.nsIIOService);
var uri = ios.newURI(url, null, null);
sss.loadAndRegisterSheet(uri, sss.USER_SHEET);

Related

How to reduce a unuse css file?

I am using bootstrap to build a mobile web page
only one page and use some of the bootstrap css and js code but I have to hold all the css and js.
since I only use some of it I want to reduce the unused css style and js code to reduce the file size
how to do it?
I mean if I only use the modal of the bootstrap how to reduce the css of col and alert and other css I do not used?
I'm not fully sure if this question really belongs here, but there is an answer to the question.
You can use Bootstrap's site to customize which elements of bootstrap you want and do not want, downloading a file with only the bits that you would like to keep.
This is available here: https://getbootstrap.com/docs/3.4/customize/
To read about it, go to their : https://www.labnol.org/internet/remove-unused-css/28635/
Remove Unused CSS from the Stylesheet
Here’s how you can easily find all the unused selectors in your CSS files in Google Chrome:
Open any page of your website inside Google Chrome and then launch the Dev Tools available under File -> Tools -> Developers Tools.
Click the Audits tab inside Dev Tools and select the “Web Page Performance” and “Reload Page and Audit on Load” options. Now click the “Run” button to begin the CSS audit process.
On the results page, expand the “Remove Unused CSS Rules” group and select the CSS file(s) that are linked from your site. You may ignore the CSS files added by social plugins and widgets since you do not have control over them.
Here you will get a sorted list of all styles that are defined in the CSS file but not used anywhere on the current page.
You can copy and save the results in a text file and repeat the steps for couple of other pages on your site. This is essential as not all selectors may be used on all pages. You can find the count of various selectors in the combined resultset, maybe using Google Sheets, and the selectors with the highest count can probably be “safely” removed.
read more this link
Chrome DevTools has coverage tool. It identifies which code is useful and which is not. I used it to reduce my css file from ~25K lines to ~2.3k lines.
Read more here: https://developers.google.com/web/tools/chrome-devtools/coverage

Save multiple <img> with all css applied elements from self DOM to jpg/png file

I developed a project on Laravel and Vue Js. In a part of this site, I have made an App in Vue whom allow the user to drags a <img> tag on another <img> tag, both contained in a DIV.
There are many (and the most unsupported) CSS applied to both images, as filters, 3dtransforation, mask, background-source...It works smooth on both Chrome and Firefox.
What I have to do now, is to save in jpg/png the "result" of all the trasformations applied to those two images, or to say it better, the html of the div container have to be converted in a image file and saved on server/rendered on the page after a click.
I didn't realise this will have been the hardest part.. Whatever I tried until now didn't worked. I tried using
Domtoimage -> The problem that I have with this javascript library is that I'm loading 1 image from the server (local currently) and 1 image from an S3disk on the AWS, and there are cross-browser compatibility problems.
Browsershot -> The issue experienced for me here is again about having the files on different storages, but here the problem is on the localhost. Hww, doing a try with both image on S3, some of the CSS properties are not rendered (mask, opacity, transform)
HTML2CANVAS -> Again both issues: cross origin, and not rendering most of the required CSSs.
At this point I really not longer know where to look out for a solution. It seems that for as easy is to set the css for two elements that works, it's impossible to ask java or the server to just "print out" what you see, exactly as you are seeing it.
About "printing": I noticed (trying to find a workaround) that even if by pressing print page, on the preview, some CSS are missing, while they are clearly visible in the page.
I'll be definitively grateful if somebody have any suggestion
As I said in comments, here are some solutions. About the solution that involves wkhtmltoimage in server side, is as follow:
wkhtmltopdf and wkhtmltoimage are open source (LGPLv3) command line
tools to render HTML into PDF and various image formats using the Qt
WebKit rendering engine
Download and install wkhtmltopdf wich includes wkhtmltoimage
Send from client all what you need (more detail below)
In backend create a html file with all what you need, you could include css and javascript
run wkhtmltoimage http://yourHtml.html yourdesiredImage.jpg
You have your page with all rendered like a browser in yourdesiredImage.jpg
As you have to send to backend some behaviors that users perform with css,
you could use window.getComputedStyle(element) to store all properties applied to an element into an object.
You have to send the object created by window.getComputedStyle(element) to the backend with ajax and reapply the rules.
To reapply those styles you could use something like:
var stylesComputed = {}//My object from frontend
var source = document.getElementById("source");
var target = document.getElementById("target");
var copy = document.getElementById("copy");
copy.addEventListener("click", function(){
var styles = "";
for(let i = 0; i<stylesComputed.length-1; i++){
styles += stylesComputed[i]+":"+stylesComputed[stylesComputed[i]]+"; ";
}
target.setAttribute("style", styles);
document.getElementById("t2").innerHTML = "Target (copied)";
});
full example here: https://jsfiddle.net/5c9rhxbn/

Difference between bootstrap.css and web.css file?

I was following this tutorial on Microsoft's developer network concerning using asp.net and mvc model with sql database. Here is the link to the tutorial that I was following
http://www.asp.net/mvc/tutorials/mvc-5/introduction/getting-started.
So basically, I wanted to play around with the design of the file which is defined in these three files bootstrap.css, bootstrap.min.css, and web.css.
As to my understanding , bootstrap is an html, css, and javascript framework which has the design for the elements already defined. In Visual Studio, I began to edit the bootstrap.css file by changing background-color of the jumbotron element. However, when I saved the file and ran my web application , I noticed that the color remained the same and did not change. But, when I defined the design for the .jumbotron element in the web.css file, the element's background color changed accordingly to red.
Essentially, what I want to know is if bootstrap.css is restricted for editing within the template?
What is Bootstrap
I think you're trying to refer to the Twitter Bootstrap that is used all around the Internet. It contains most of the Styling techniques for the Elements, such as buttons, inputs etc.
When you edit a website's Stylesheet, (Bootstrap.css is a Style sheet and its name doesn't make it write/edit protected file) you get the style that you've applied to it.
http://getbootstrap.com/
Web.css
This file might be the default Style sheet that was created by the Developers at Microsoft while creating the Template for the Website that you're using.
Secondly, when you edit and create this file, it is also a Style Sheet which means it would apply the style to your website and all the web pages who are refering to it.
You're right. It has all the pre-defined methods and contains all of the contents and styles required to make a web page responsive. For more: https://en.wikipedia.org/wiki/Responsive_web_design
What might have caused this problem would be cache. When you first loaded the web page, it would have captured the New Style sheet from the file System and would have applied the styles. But second time it would have loaded the File from the Cache.
https://en.wikipedia.org/wiki/Cache_(computing)
This way, the browser would load the last successive layout of the Web Page. Without loading a new StyleSheet from the File System.
I really think, you need to reload the page using CTRL + F5 button. This would be helpfull in this manner! Because Bootstrap.css is editable and you can edit it. It doesn't prevent editing, only caching would be the problem here.

Content style is not getting applied to text files from GitHub

I made Google Chrome extension which inserts (by default hidden) text area into document.
It appears on all pages. It's ok when page is HTML, but on other pages it's unuseful. For example, when I open https://raw2.github.com/github/hubot/master/README.md, I can see textarea, even it has display: none !important styling (via class). It should be hidden, but it isn't.
How to prevent that weird situation? Maybe to check document type (is it HTML)?
It seems that content script styles are not applied to files served with MIME-type text/plain. This is clearly a bug, so I have reported it on Chromium's bug tracker, see issue 333234 .
A work-around to the problem is to insert a plain <style> element in the document:
document.head.appendChild(document.createElement('style'));
This does not work in your specific example, because inline and external style sheets are blocked by Github's Content Security Policy (default-src 'none').
The only work-around I can think of is to directly apply the style sheet via JavaScript:
textarea.style.display = 'none';
// Or,
textarea.style.cssText = 'display:none;';

IE7 and IE8 randomly not able to load external script

I am dynamically adding <link> elements to the head once the DOM is ready. However, I'm getting inconsistent results in IE8 and IE7 (all other browsers are fine).
Every few times the page is loaded (cached or uncached), IE 7/8 will drop a handful of CSS rules in the stylesheets. 1 or 2 of my dynamic stylesheets will not load. It's always the same 1 or 2 stylesheets that IE tends to ignore - even though the Developer Toolbar shows them as added to the head!.
The stylesheets themselves show up as <link> elements in the final DOM, but some of their rules are not applied (although every few reloads they are applied, without any issue).
In my position, I do not have the luxury of writing code from the <head> (CMS restriction) - I can only dynamically insert from the body, which may be the issue.
UPDATED: This is the code I am using (located within the <body>) to insert stylesheets:
document.observe('dom:loaded', function() { // Using Prototype.js
// Add stylesheets
// addStylesheet('cite.css', 'head'); // Contains no webfont/#font-face rules
// addStylesheet('type.css', 'head'); // Contains webfont family name references*
// addStylesheet('flex.css', 'head'); // Responsive rules with #media queries
// addStylesheet('anm8.css', 'head'); // Some minor positional CSS for home page
// addStylesheet('gothic-cite.css', 'head'); // *Contains #font-face config
// addStylesheet('stag-cite.css', 'head'); // *Contains #font-face config
addStylesheet('all.css', 'head'); // Contains ALL content from above in 1 file
function addStylesheet(cssname, pos2)
{
var th2 = document.getElementsByTagName(pos2)[0];
var s2 = document.createElement('link');
s2.setAttribute('type', 'text/css');
s2.setAttribute('href', cssname);
s2.setAttribute('media', 'screen');
s2.setAttribute('rel', 'stylesheet');
th2.appendChild(s2);
}
});
As suggested, even when I combined all rules into one stylesheet (which I hate doing), IE 7/8 continues to flip-flop as described with some rules, and the page appears differently.
As a further check, I also removed all #font-face and referenced font-family: "webfont-name" rules from the stylesheets, and the same behavior continued. Therefore, we can rule out webfonts being the issue.
You can see the anomalies by visiting the following with IE8 and refreshing/clicking the nav several times. It seems completely random as to when IE8 is dropping those styles. However, in the natively-built control page, all styles load correctly, every time.
Live Page (with problems)
https://www.eiseverywhere.com/ehome/index.php?eventid=31648&tabid=50283
PHP-based CMS prints out XHTML on page load (template content mixed w/user content)
Prototype.js is loaded and initialized by default on page load
CMS proprietary scripts.js file is parsed on page load
My scripts run when DOM is loaded, essentially replacing body.innerHTML CMS fluff-HTML with just the HTML I want, then adds stylesheets to <head>.
For lte IE 8, CSS extension plugins (selectivizr.js, html5.js, and ie-media-queries.js) are loaded within the <body> via conditional comments. Not sure if they wait for DOM:loaded...
The CMS WYSIWYG editor converts all carriage-returns to empty <p> tags, resulting in elements like <section> being contained inside broken <p> tags, and extra <p></p> tags being created where whitespace is expected. Only lt IE 8 seems to choke on this, however, so I added the following CSS rules to remedy this:
:not(.ie7) p { display: none; }
.ie7 p { display: inline; }
article p { display: block !important; }
I should note that the external stylesheets here are being pulled from the same domain, but each time they are re-uploaded, a new MD5-based URL is generated for the file. I'm not sure if previous revisions to the file (or previous files) are still available by their previous URLs. This isn't likely to be the problem though, since the newly created all.css stylesheet is still dropping rules that have been in the file from the start.
Control Page (works flawlessly)
http://client.clevelanddesign.com/CD/IDG/CITE/home.html
Pure XHTML document - no PHP.
jQuery is used, rather than Prototype, for IE8 and below.
All resources (stylesheets) are present in <head> at page load - no dynamic insertion
For lte IE 8, CSS extension plugins (selectivizr.js, html5.js, and ie-media-queries.js) are initialized natively.
Rephrased question:
Which of these differences do you think may be causing IE 7/8 to flip-flop on styles when loaded on the Live page? I personally suspect either a race-condition issue, or that Prototype.js and the other CMS scripts are mucking things up (unfortunately no way to purge those from the page though).
PS: I've already tried using IE's createStylsheet() function, to no avail.
UPDATE - Screenshots of working/not working in IE8
IE8: DOM code when loaded correctly:
IE8: DOM code when NOT loaded correctly:
I've nailed down exactly what is happening, but still do not know the cause of flip-flop:
selectivizr.js is not loading correctly every few page loads.
All of the rules that use CSS3 selectors need that script to be applied in IE 7/8. Therefore when IE 7/8 does not load selectivizr.js correctly, those rules are ignored. Those rules certainly include the webfont references, as well as the errant <p> display properties.
To remind you all, these helper JS scripts are being loaded normally (from within the <body>) with the initial page load, before my script replaces the <body> contents (including that script reference). Therefore, there's a chance it's initializing twice (can anyone confirm this?)
The trouble is, on the control website, selectivizr.js always loads correctly in IE 7/8. There are also no known incompatibilities between the CSS3 helper js and the Media Query help js files (when initialized correctly).
I removed selectivizr.js from the page and the page loaded exactly the same way after 20+ refreshes. Good to get consistency back, bad that I've lost my CSS3 rules in IE 7/8.
Apparently this is how the js plugin in question works:
In accordance with the W3C specs, a web browser should discard style
rules it doesn’t understand. This presents a problem — we need access
to the CSS3 selectors in the style sheet but IE throws them away. To
avoid this issue each style sheet is downloaded using a
XMLHttpRequest. This allows the script to bypass the browsers internal
CSS parser and gain access to the raw CSS file.
Source: http://www.css3.info/css3-pseudo-selectors-emulation-in-internet-explorer/
I can try any suggested CSS3-selector plugins that you all may have; maybe one will load more reliable, or have less overhead and thus less room for lag-related issues. Any alternatives?
Or, perhaps I should add it after the DOM is ready the second time (after my script replaces the body contents) to the <head> or elsewhere in the <body>. None of these options worked - they had the same if not worse outcome.
First off let me say I have worked on multiple initiatives where the teams have started down the path of dynamically generating the DOM via Javascript, including remote-loading of scripts through CORS.
After many months of effort on 3 different projects (and different approaches used in each), we finally had to face the fact that IE7 and IE8 are incapable of properly or consistently dynamically loading and processing external scripts or CSS.
My recommendation is to consolidate / combine any scripts on the PHP / server side and serve up as a single file that can be cached on the client side.
As an additional note, IE is not completely to blame. There are huge complexities involved with downloading, processing, and rendering scripts / css in the correct orders and programming this process such that it works well in every environment (webkit + mozilla + IE9+) requires near-expert-level knowledge and very thorough testing.
In your case, one example of bad "flow" is the fact that when I viewed your page specifically, it briefly shows the non-CSS-applied page (yucky!) before the screen "updates" and CSS gets pulled in and applied. Bad bad bad.
Other issues I noticed are the large number of httprequests in general. Each requires a DNS lookup, cache / expires check (and other stuff dictated by headers), and subsequent download of response. On desktops this is not all that noticable, but on mobile devices, tablets and even some slower / bogged-down PC's it is especially noticable.
If you're building a web app in today's browsing environment and have only a small team, it's probably best to either:
Serve up CSS as a single, cacheable file from a CDN, and pages in pre-parsed, pre-iterated, pre-rendered HTML chunks, minimizing the client-side JS processing (only binding elements post-load), or
Go with a pre-existing client-side framework such as Sencha, SproutCore, YUI etc. - they have built out the framework for you and fixed all the bugs already.
Two things have to happen before I change my view: IE8 has to disappear from general use (drops below 10%), and the "average" mobile device needs to have 2 physical processor cores. Right now only the expensive / high-end models have dual-core processors.
Also of note, the fastest mobile processors even with JIT JS compilers are still 10x slower than a typical desktop in JS performance - which when compared directly to a desktop, would compete head-to-head with a Pentium 4 or old AMD Athlon 64.

Categories