Remove file that contains specific string in href via JS - javascript

In HubSpot a file called layout.min.css is automatically added and is you cannot disable this css file anywhere in the CMS.
As such, I've tried to remove() and disable the file via JS, but the styles from that css file are still being rendered.
When I view source, this file looks like this:
<link rel="stylesheet" href="//cdn2.hubspot.net/hub/xxxxxx/hub_generated/template_assets/1642616240355/hubspot/hubspot_default/shared/responsive/layout.min.css">
Now, notice the 1642616240355 in the URL? That number (for some reason) changes everyday.
Yesterday, I had the following running, and it removed the file:
$("link[href='//cdn2.hubspot.net/hub/xxxxxx/hub_generated/template_assets/1642528871696/hubspot/hubspot_default/shared/responsive/layout.min.css']").attr('disabled', 'disabled');
$("link[href='//cdn2.hubspot.net/hub/xxxxxx/hub_generated/template_assets/1642528871696/hubspot/hubspot_default/shared/responsive/layout.min.css']").remove();
However, as it keeps changing, I'm now looking to remove and disable any css file that contains layout.min.css in its href.
I'm aware that there's a :contains selector, which might be of use here, but unsure on how that would be implemented? As in, how would I tell the code to look at all stylesheets and remove the one that contains "layout.min.css" in its href?
Have also tried:
<script>
const stylesheets = document.querySelectorAll('link[rel=stylesheet]');
for (var i = 0; i < stylesheets.length; i++) {
if(stylesheets[i].href.indexOf("responsive/layout.min.css") >= 0) {
stylesheets[i].disabled = true;
stylesheets[i].remove();
}
}
</script>
But it still shows the layout.min.css when viewing source.

I would recommend you to do this with pure JavaScript instead of JQuery. Because otherwise you have to wait until the JQuery library is loaded.
Use this code for that:
const cssElement = document.querySelector("link[href*='layout.min.css']");
cssElement.disabled = true;
cssElement.remove();

Based on the code you provided that you said works, why not use the ends-with matcher: $=?
$("link[href$='layout.min.css']").remove();
That'll find all the <link> HREFs that end with 'layout.min.css' and remove them, which is exactly what you're describing as your goal.

Related

How to target CSS link with JavaScript

I only have access to the back end of my CMS. They are loading the custom style sheet this way
<link rel="stylesheet" media="(min-width:481px)" href=".../css/custom/styles.css" type="text/css">
I need to remove the media="(min-width:481px)". Is there a way to do this with JavaScript (I don't think the CMS uses jquery)?
I personally do not recommend messing with the elements of a link with JavaScript, but if you still want to do it, this should work:
document.querySelector('link[href=href=".../css/custom/styles.css"]').removeAttribute('media');
If you still want to do this, make sure to wait for css styles to load.
If you want to go with this solution for some reason and do it for all link tags, then this one is simple:
var linkList = document.querySelectorAll('link');
for(var i in linkList) {
linkList[i].removeAttribute('media');
}
Always use .removeAttribute, instead of using setAttribute to set the argument to null. That is generally bad practice.

how can I detect page when I compile all javascript to one file

I compile all my javascript for different pages into one file, so I have to identify page for my all.js. I can put a hidden element in my pages and let javascript detect this element, but I don't like this solution, are there any other ways to do this?
You could go by the url using location.href (or another field from the location object).
However, a better approach is using a data- attribute on the body tag, e.g. <body data-page="whatever"> and then using $('body').data('page') to retrieve the value.
If you script is based on pages, then compiling them into one script is a bad idea, load the file separately, it will be lighter and definately increase some performace.
I am not sure, why do you need this, but in general it is not good practice to change dynamicaly change content of javascript file, since you are disabling javascript cacheing, what can be performance issue later.
Any way, you can solve it from other side, what about using all.js just to detect the page, where are you and then you can use this information, to load right javascript file dynamicaly, like in the following example
document.write('<script src="'+location.pathname+'.js"></script>');
Which will load same file as you are on, just with .js extension. So for example on index.html page it will load index.html.js file
I almost always use MVC frameworks and tend to put my action and controller as classes on the body element
<body class="main_controller index">
Which lets you do things like this:
$(document).ready(function(){
//Only for lessons#search
if (!$(body).hasClass('lessons search')) {
return;
}
function close_style_filter_box() {
$('#style_filter_box').slideUp();
}
});
$(document).ready(function(){
//Only for main_controller#index
if (!$(body).hasClass('main_controller index')) {
return;
}
function do_something_else_on_this_age() {
....
}
});
Another way is using javascript variable:
var PAGE = 'page1';

Create new (not change) stylesheets using jQuery

We've got a little tool that I built where you can edit a jQuery template in one field and JSON data in another and then hit a button to see the results immediately within the browser.
I really need to expand this though so the designer can edit a full CSS stylesheet within another field and when we render the template, it will have the CSS applied to it. The idea being that once we've got good results we can take the contents of these three fields, put them in files and use them in our project.
I found the jQuery.cssRule plugin but it looks like it's basically abandoned (all the links go nowhere and there's been no development in three years). Is there something better or is it the only game in town?
Note: We're looking for something where someone types traditional CSS stylesheet data in here and that is used immediately for rendering within the page and that can be edited and changed at will with the old rules going away and new ones used in their stead. I'm not looking for something where the designer has to learn jQuery syntax and enter in individual .css("attribute", "value") type calls to jQuery.
Sure, just append a style tag to the head:
$("head").append("<style>p { color: blue; }</style>");
See it in action here.
You can replace the text in a dynamically added style tag using something like this:
$("head").append("<style id='dynamicStylesheet'></style>");
$("#dynamicStylesheet").text(newStyleTextGoesHere);
See this in action here.
The cleanest way to achieve this is by sandboxing your user-generated content into an <iframe>. This way, changes to the CSS won't affect the editor. (For example, input { display:none; } can't break your page.)
Just render out your HTML (including the CSS in the document's <head>, and write it into the <iframe>.
Example:
<iframe id="preview" src="about:blank">
var i = $('#preview')[0];
var doc = i.contentWindow || i.contentDocument;
if (doc.document) doc = doc.document;
doc.open('text/html',true);
doc.write('<!DOCTYPE html><html>...</html>');
doc.close();
If the user should be able to edit a whole stylesheet, not only single style attributes, then you can store the entered stylesheet in a temporary file and load it into your html document using
$('head').append('<link rel="stylesheet" href="temp.css" type="text/css" />');
sounds like you want to write an interpreter for the css? if it is entered by hand in text, then using it later would be as simple as copy and pasting it into a css file.
so if you have a textarea on your page to type in css and want to apply those rules when you press the button, you could use something like this (only pseudocode, needs work):
//for each css id in the text area
$.each($('textarea[name=cssTextArea]').html().split('#'), function({
//now get each property
$.each($(this).split(';'), function(){
$(elem).css({property:value});
});
});
then you could write something to go through each element that your designer typed in, and get the current css rules for it (including those that you applied using some code like the snippet above) and create a css string from that which could then be output or saved in a db. It's a pain and much faffing around with substrings but unfortunately I don't know of a faster or more efficient way.
Hope this atleast gives you some ideas

jQuery - dynamically remove head elements on click

Does anyone know if you can remove head elements on a button click and how to do it with jQuery?
I am trying to get rid of certain script tags from the html head when a button is clicked.
For instance. I have 1 screen view with a slideshow controlled by an external javascript file. When I click on a button "Click to get rid of this elements JS" I want to remove the external javascript path from the HTML Head.
Any ideas. Have been at this thing for a week or so.
You can add an id to a script element then remove that ID:
<script type="text/javascript" src="init.js" id="initJs" ></script>
<span id="removeScript"></span>
$('#removeScript').click(function() {
$('#initJs').remove();
});
You can do this sort of thing using javascript, sure, but before you do it, you might want to ask yourself again why. Here's a link describing how to do it in pure javascript with a jquery example provided by the other answerer:
http://www.javascriptkit.com/javatutors/loadjavascriptcss2.shtml
But try to keep in mind that most modern browsers will keep these external resources in memory for at least as long as the page is open. Therefore, you won't really be doing much.
I don't think its a good Idea to remove Entire HEAD Element. 'Cause your Page may contain some more Elements (i.e., title, style..) which are appended to Head Element. If you want to remove a particular script Element do something like
$(function() {
$('input[type=button]').click(function() {
$('script[src=path/file.js]').remove();
});
});
Edit :
var flag = false;
function breakTheCode() {
if(!flag) {
//run your code
}else return;
}
$(function() {
$('input[type=button]').click(function() {
flag = true; //flag is set, so we no more using/ running your code
breakTheCode(); //call you function/method
});
});
For my part the best solution is to use ID on the scripts.
I read many page over the web, try many solutions, and the only one who works fine every time is to remove a script like a div with an id !
For remove js file : $("script[src='your.js']").remove();

How can I use javascript to convert relative href attributes into absolute paths?

I have a template that gets screenscraped from an outside vendor and need to include absolute paths in the navigation so the externally hosted content will properly link back to our site.
Right now the page/template is driven by a global menu app written by our back end development staff... so anyone who updates our site goes in and changes the menus and their paths...
Right now all of the links are linking to relative paths back to the root.
For example
Home
News
Media
Other
I need a simple way (preferably with jquery) to prepend "http://www.domain.com" to each of those links.
Please note that jQuery object $("a").attr("href") is not equal to $("a").get(0).href ?
$("a").each(function() {
alert(this.href);
$(this).attr("href") = this.href;
});
In you case, this may not help you , because you want static markup, javascript generate dynamic content. But it seems that you want static markup in that case it has to be emit by server.
$('a').attr('href', 'http://www.domain.com'+$(this).attr('href'));
I don't recommend using javascript to solve this issue. This should be solved in the page template. However, if you still want a jquery solution then here you go. Assuming those links have a specific class that distinguish them from internal links:
$('a.external').each(function() {
$(this).attr('href', domain_name + $(this).attr('href'));
})
you don't need jquery for such a simple function....
var elements = document.getElementsByTagName("a");
var eachLink;
for (eachLink in elements) {
var relativeLink = eachLink.href;
var absoluetLink = ["http://",domainName,"relativeLink"];
eachLink.href = absoluteLink.join("");
}
something like this should work, and it runs much faster and you won't need to load the entire jquery library just to run 6 lines of code :P
It's very simple:
$('a').each(function(){$(this).attr('href',this.href);});
When you read the href property of a HTMLAnchorElement, you get the absolute path, so you can overwrite it with attr() method of JQuery.
I noticed that all the solutions here only work with href attributes that begin with a "/" character. If you want something more robust, you may want to try the js-uri library. It looks cool but I haven't tried it myself so I don't know how buggy it is.

Categories