Block specific javascript statements from executing "globally" from a client side perspective - javascript

Dear Stackoverflow Community,
as you might see, this is my first post and a rather specific question I believe.
Here is the problem:
It is possible to block javascript as a whole or specific scripts as far as i could find out. What however if i globally want to stop the execution of specific javascript statements?
Practical example:
A website is utilising several javascripts many of which are useful and I would like to participate in their functionality with the permanent exclusion of any code that references overflow:hidden. I perceive that (CSS-Snippet?) to be malicious code by design. It can be easily circumvented and fixed through executing your own code. That's not what I'm talking about though.
Probable solutions:
- Remove the browsers capability of understanding that particular code
- Enforce overflow:auto
- Apply overflow:auto when the website is fully loaded automatically
The aforementioned solutions seem very unelegant to me and as you guys seem like a clever bunch maybe you can think of something less superfluous and practical.
All the goto addons I've tried only offer 1-off solutions or the need to repeat the task of counteracting those code snippets.
Current solution:
var r="html,body{overflow:auto !important;}";
var s=document.createElement("style");
s.type="text/css";
s.appendChild(document.createTextNode(r));
document.body.appendChild(s);
void 0;
Isn't there a way to tell FireFox (or chrome) to categorically ignore every single attempt to alter overflow:auto or similarly (perceived) malicious codes?

If you really want to set a property for all the elements in the website you could try this jQuery code
$('*').attr('style', ($('*').attr('style') || '') + ";color:black !important");
Here I get all the elements in the page and add my custom property in their style. In my case it was a black color, but you can have your overflow set to auto.
Check this Fiddle and you'll see that I set many colors to the texts in the page, both with inline styles and through CSS and then the jQuery script forces all of them to be black.
The explanation is that an inline rule is more "powerful" than CSS rules, so if you set an inline rule to be important it is applied to the element instead of the CSS rule (as it overwrites it).

Related

Extract CSS rules from any given element

I'm trying to find a way to extract all css rules from any given element (I have full access to the html, and css).
I have look into other solutions such as getComputedStyle, however, it doesn't help much with certain properties such as width or height. For example, I expect it to return width: 100% when applicable, but it always return the real width value in px. What I need is the CSS rule definition, not how it is actually rendered on the browser.
My last resort is to use some css-inliner such as juicejs then I can access the element.style.prop, but I think if these js inliners can turn css rules to inline css then they must have extracted the css rules along the way already? I tried to look into its source but if there is any module out there doing the job it would be much better than trying to extract the code from that library.
It amazes me that there are not many solutions available for this issue. I ended up finding 2 solutions that both work (there are probably some edge cases but I have not encountered yet)
Option 1: A getMatchedCSSRules implementation posted here:
https://stackoverflow.com/a/37958301/821517
Pros: short and concise
Cons: does not support pseudo selectors (yet)
Option 2: A very all library called CSSUtilities mentioned here:
https://stackoverflow.com/a/12023174/821517
Pros: it can handle pseudo selectors
Cons: very very old library which relies on another library that is deprecated.
I ended up using CSSUtilities and I had to make some changes (hacks) to make it work with the new js engines. I post both modified files here in hope that it will help others (and that errors I made can be spotted and suggested with fixes)
New files: https://gist.github.com/yellow1912/c9dbbab97497ec42489be55e8abe73c7
Please ensure that you visit this link to download the package which contains the document file: http://www.brothercake.com/site/resources/scripts/cssutilities/

CSP - How to solve style-src unsafe-inline -when having dynamically positioned page elements

In our app code we allow some objects to drag and drop around the page. Also we have things like popups that need to be positioned below buttons and dialogs that we position in the page ect.
To do so we need to allow the following inline css properties
z-index
top, bottom, left, right
height, width
We cant really make classes for this, imagine left for example could be 0 to 20000 so we would need millions of classes.
I cant see any way other than inline css.
So to solve for CSP (https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP) then that means we need to fully allow style-src: unsafe-inline
I'm sure this is a common scenario. What do people do about this case? We also use veracode to scan our software so im thinking we just "mitagate" this by explaining that we only allow a set of inline css attributes.
But i would think maybe CSP should allow a certain subset of dynamic css attributes.
Has anyone encountered this and have any thoughts?
When you write CSS to elements via JavaScript using the CSSOM, it’s not the same as literally writing style=“...”; rather, you are directly manipulating the DOM [correction: the CSSOM]. CSP allows these types of styles even when not allowing unsafe-inline styles.
(See here for an example. You don’t want to add a literal “style” attribute to the element, but use the CSSOM — https://stackoverflow.com/a/29089970/339440 )
Unfortunately, there's currently no "clean" way of doing this. CSP doesn't currently have any way of inspecting style attributes to determine if they're safe; it's unclear that this is possible at all, as almost any CSS attribute could be used to create misleading or otherwise unintended content on a site.
The options I see are:
Use a CSP nonce to allow inline style attributes on selected elements. This is similar to unsafe-inline, but more selective (and hence a bit safer).
When CSS attr() is implemented in all common browsers, you :
/* ATTENTION: This is not a working example; see below */
.position-by-attr {
left: attr(data-left px);
top: attr(data-top px);
}
<div class="position-by-attr" left="123" top="456"> … </div>
However, note that this feature is not currently implemented in any browser. It is present in the CSS3 specification, but has not been implemented. It may be years (if ever) before it is practically usable.

When should I control background image change with CSS vs Javascript? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
This is more of a general practice question that a problem specific one but I'll give an example of what I mean. There are a lot of things you can control with CSS that you can also do with Javascript, but is one better to lean on than the other?
Example:
I have four buttons in a nav that are given a class of "selected" when the section they're associated with is in view. So I could either write a CSS statement for each button (or have Sass do it for me with a mixin)
#home-butt.selected{
background-image: url(images/home-up.png);}
#about-butt.selected{
background-image: url(images/about-up.png);}
#work-butt.selected{
background-image: url(images/work-up.png);}
#contact-butt.selected{
background-image: url(images/contact-up.png);}
Orrr I could write something in javascript to do the same thing. (*I gave the images a title attribute that matched the image name so it could pull from there).
title = $(this).attr('title');
$(this).find('img').css("background-image",
"url(" + 'images/' + (title) + '-up.png' + ")");
So my question is which is better to use? Is it the javascript because it's less lines of code? Or the CSS incase javascript is disabled? Or is this a very situational question where there isn't always a right or wrong answer?
Opinions and rebuttals are welcome!
To answer your question about "is one better to lean on than the other?"
Keep in mind, that CSS has a specific purpose. To apply the look to your application. JavaScript on the otherhand, is mostly the feel of your app. Always prefer CSS over JavaScript when editing styles.
The only time that you ever should modify styles using JavaScript is when you have a dynamic application, and need to change styles based on some unknown variable. Even then, a lot can be achieved with just using CSS.
Also keep in mind that you are using jQuery. think about jQuery's constructor. it is a CSS selector.
With the concept of CSS pseudo-classes introduced, there is very little that you cannot achieve style-wise with CSS.
In many cases where Javascript developing makes what I'm trying to accomplish much more easy and other cases where CSS does that to.
" In the end each "language" has its appropriate place in web development and used wisely can enhance both development and user experience. Learn what those uses are (I recommend experience learning) and apply wisely. In my experience, set in stone rules such as "Never use JS when a CSS solution exists" (paraphrased) are rarely best in the practical world. "
If you are working with layout, use CSS, if your creating the look and feel use CSS, if your doing animations use CSS3
If you attach event handlers or reacting to user input use JavaScript.
Usually you want to use CSS, because it's much faster than javascript. Also there are going to be users with javascript disabled, which aren't going to see your enhanced presentation if it relied on js function.
The usual answer is, use CSS when you can, because it will work with JavaScript disabled, and also because you don't have to deal with issues like waiting for elements being available in the DOM before referencing them.
But sometimes it depends. Keep in mind that:
Depending on the selector or properties you're changing you may have issues with browser compatibility.
If you're changing the image like in your example, you may see it flicker while the new image is loaded. You can avoid that by using a sprite image, or preloading the images with JavaScript.
As a general rule of thumb, I would use CSS for styling and JavaScript only to "make the page alive".
So the best and the most ideal use of JavaScript is to add and remove classes from elements
- classes, which your CSS is depend on.
Loading the jQuery library to perform this simple task is unnecessary and relying on javascript to apply background images to your img tags is unnecessary as well.
If it can be done properly in CSS, and work in all browsers, then it should be done in CSS.
Javascript is for more advanced or complex tasks, which require interaction or animations that CSS can't provide for all browsers (due to cross browser compatibility issues - check out caniuse.com)
In your example, if the .selected attribute is being given dynamically by javascript for instance:
makeSelected(elm)
{
document.getElementById(elm).className='selected';
}
then i would still personally add the styling for .selected in CSS instead of adding the image through javascript.
If you're adding .selected based on the current page you're on and not through javascript then I would recommend using CSS.
I prefer CSS over Script for one main reason Browser compatibility
There are just soooo many times when one script code or the other isn't compatible in one browser or the other (cough or just IE)
With css I haven't had such issues yet (touchwood) and also if there were any issues CSS's won't affect as much as script's which just don't let any other following codes to execute.
Let me provide my opinion.
Personally I don't believe a website should have a lot of "gimmicks" in terms of designing.
BY gimmicks I mean hovering effects, music in the background(absolute no-no) or other "eye-catching details". All of this looks good the first time but subsequently visitors get fed up with this distractions.
Without deviating from the main issue. CSS/JavaScript for styling.
Well they do exist hand in hand. The best example for this would be Bootstrap library. Although I have never used it personally but it seems amazing what can be achieved using CSS and JavaScript.
So, We will need both to design spectacular website. CSS helps in the basic designing and to make the website more responsive we use JavaScript and its derivative libraries like Jquery for all the finer looking stuff

Questions about JavaScript and a vertical, multi-level navigation bar

Is it possible to make a vertical, multi-level navigation bar using only CSS and WITHOUT using JavaScript?
Like the one in here:
http://www.dhtmlgoodies.com/scripts/slidedown-menu2/slidedown-menu2.html#
I am trying to avoid using JavaScript because browsers today has an option that can disable JavaScript codes. I don't want my webpages to be broken because of that settings. Should I even be thinking about this? Or should I just use JavaScript anyway?
I was hoping on using only CSS for this, though I'm not sure if CSS is enough for this.
EDIT: By the way, is there a CSS selector when you click an <a> tag? Something like 'a:click'. I only know a:hover.
You won't be able to have any sort of animation like that example, unless you use CSS3 animations, in which case you will have LESS support than if you used JavaScript.
If it were me, I would just use JavaScript to do it. If the user has it turned off, they will still receive the menu, just not the animation (if you code it correctly).
There are some examples here of what you can do with CSS:
http://www.cssmenus.co.uk/dropdown.html
CSS is mainly for styling your webpages, while JavaScript is mainly for giving them different behaviors and interactivity.
That said, CSS3 is doing a lot to change that. But, if you want a web page with any kind of Cross- browser support currently, that's not really an option.
Like you have said, users have the option of disabling JavaScript, which is a good thing for security. This, however, means that you should always try to make any JavaScript supplementary to your page, so there is still some functionality even if JavaScript is disabled.
If you want any interesting effects in your menu, you will need some mix of CSS and JavaScript, and if you define and apply your styles within your CSS documents and not from within your JavaScript, you will still sustain some level of usability

Javascript widget implementation

I have a question about Javascript widgets. The widget I am working on simply embeds content on a page instead of using iframes. So far it looks good. But there are cases where some users layouts are messing up the widget. For example, the widget might require a width of 300px to appear. But the parent div is set to 250px and hence the right part of the widget is cut off.
I was wondering what sort of precautions should be taken to prevent this? I was talking to the product manager who mentioned he wanted me to check the parent div elements and get the size and then show an alternate message if their size is not accurate. But again, since this is Javascript and the widget is supported in many diff browsers(including IE6), I am wondering how fail-safe this method would be? What if I need to iterate the DOM all the way up before getting a valid size? I am also worried about performance here. This extra checks would slow down the delivery of my widget content to "good users" since I am adding a layer of complexity to all users. I don't want to penalize good users just because of the few errant ones.
I am not using any sort of JS library here, so any solution should not suggest the use of one. Also, the reason for not using a library was simply not to add extra weight to the page load to deliver a widget. I understand that "jquery" for example is small, but in my case, even 24k compressed seems like an overkill for a widget delivery that contains no core code for the widget.
Has anyone dealt with such issues before? What are your solutions to these?
There are reliable ways of determining the size of an element using JavaScript. You're quite right that you may need to iterate up the tree in some cases, but the answer you get will ultimately be quite valid.
Although you don't want to directly include any library code in this project, you may consider looking at how the major libraries implement their "what's the width of this element" functions to drive your own implementation.
Beware of quirks mode too.
I'd check to see of the page has Jquery, if not load it into the page using no-conflict mode. Then use jQuery to examine the page.
See: How to embed Javascript widget that depends on jQuery into an unknown environment

Categories