As you know, the correct fix here is to fix those links server-side, ideally by removing the scheme entirely, to create scheme-relative URLs like this:
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
But you’ve said you can’t do that.
So:
- You can readily find all
a
elements viadocument.querySelectorAll
. - You can easily loop through the result.
- …and get their
href
viagetAttribute
(or the resolved URL via thehref
property) - …and update it if necessary (via
setAttribute
or thehref
property). - Similarly,
script
andlink rel="stylesheet"
.
Here’s a simple example for links:
Array.prototype.forEach.call(
document.querySelectorAll("a[href]"),
function(link) {
if (link.href.startsWith("http://")) {
link.href = "https://" + link.href.substring(7);
}
}
);
Ensure that’s in a script
tag at the end of </body>
so that the elements exist as of when it runs.
Generalize as needed for img
(the src
property), script
(the src
property), link[rel=stylesheet]
(the href
property), … (Each of those is a valid CSS selector which will work with querySelectorAll
.)
2
solved change protocol of urls on webpage via javascript [closed]