I am adding an external CSS file and an external JS file to my headers and footers.
When loading an HTTPS page, some browsers complain that I am loading unsecured content.
Is there an easy way to make the browser load the external content via HTTPS when the page itself is HTTPS?
Use protocol-relative paths.
Thus not
<link rel="stylesheet" href="http://example.com/style.css">
<script src="http://example.com/script.js"></script>
but so
<link rel="stylesheet" href="//example.com/style.css">
<script src="//example.com/script.js"></script>
then it will use the protocol of the parent page.
nute & James Westgate are right when comenting on the later answer.
If we take a look at miscelanous industry-grade external javascript includes, the successfull ones use both document.location.protocol sniffing and script element injection tu use the proper protocol.
So you could use something like :
<script type="text/javascript">
var protocol = (
("https:" == document.location.protocol)
? "https"
: "http"
);
document.write(
unescape(
"%3Cscript"
+ " src='"
+ protocol
+ "://"
+ "your.domain.tld"
+ "/your/script.js"
+ "'"
+ " type='text/javascript'
+ "%3E"
+ "%3C/script%3E"
) // this HAS to be escaped, otherwise it would
// close the actual (not injected) <script> element
);
</script>
The same can be done for external CSS includes.
And by the way: be careful to only use relative url() path in your CSS, if any, otherwise you might still get the "mixed secure and unsecure" warning....
If you use relative paths ( and the content is on the same domain) then the content should use whichever protocol the page was requested in.
However if you are going across domain to a CDN or resource site, or if you need to use absolute paths, then you will need to use server side script to change the links, or always use https://
In contradiction to the escaped response (which will also work) you could skip that part and use the correct way to add nodes to your dom tree:
<script type="text/javascript" language="javascript">
var fileref=document.createElement('script');
fileref.setAttribute("type","text/javascript");
fileref.setAttribute("src", document.location.protocol + '//www.mydomain.com/script.js');
document.getElementsByTagName("head")[0].appendChild(fileref);
</script>
But the protocol-relative path would be the way to go.
Related
I am using the Virtual Keyboard (Deprecated) from Google in my current project. Unfortunately it loads some additionale js-resources from an insecure source. Is there a way to force the script to use https instead of http?
The problem is the language file which is used to display the correct letters. The stylesheet e.g. is loaded over https.
Here is my script:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Virtual Keyboard | Google APIs</title>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
</head>
<body>
<input id="language">
<script>
google.load("elements", "1", {
packages: "keyboard"
});
function onLoad() {
var kbd1 = new google.elements.keyboard.Keyboard(
[google.elements.keyboard.LayoutCode.SWEDISH],
['language']);
}
google.setOnLoadCallback(onLoad);
</script>
</body>
</html>
Update:
The only resource, which is loaded over normal http is the language-file, in this case the swedish version.
The language-file is loaded in the function onLoad during the var kb1 = new google.....
Based on the answer to another question
it seems possible to redefine the src property of a <script> element, which is used to load
the javascript code for the swedisch keyboard. If you make sure the following code is executed
before the new google.elements.keyboard.Keyboard call, the http will be replaced by https.
From the network info in the chrome debug console, this indeed seems to load the keyboard
settings over https.
Object.defineProperty(HTMLScriptElement.prototype, 'src', {
get: function() {
return this.getAttribute('src')
},
set: function(url) {
var prefix = "http://";
if (url.startsWith(prefix))
url = "https://" + url.substr(prefix.length);
console.log('being set: ' + url);
this.setAttribute('src', url);
}
});
Just setup your script url like this and it will work!
<script src="//www.google.com/jsapi"></script>
This is the url relative protocol
The type"javascript" part is not anymore necessary as it is taken as javascript if nothing is specified, so save space! MDN element script
this code is not working as expected
<html>
<head><title>alert()</title>
<script type="text/javascript">
function greeting()
{
var name=prompt("what's your name?","your name");
if(name){
alert("hi, " + name + " welcome to this page");
document.getElementById("im").src="F:\wallpapers\a.jpg";
}
}
</script>
</head>
<body onload="alert('hi, this is the alert() function');">
<img id="im" src="F:\wallpapers\Ubuntu_wallpaper__1_by_leroi14.jpg" onclick="greeting();" /></body>
</html>
document.getElementById("im").src="F:\wallpapers\a.jpg" is not displaying the image when given absolute path.
But it works if image is in same folder as this file.
can anyone help?
For whatever reason you use backslashes in your path, which need to be escaped in string literals:
"F:\wallpapers\a.jpg" === "F:wallpapersa.jpg"
Use "F:\\wallpapers\\a.jpg" or "F:/wallpapers/a.jpg" instead.
If you plan on serving this page to others, you don't want to use an absolute path. Javascript runs on the browser, and does not have access to the server's filesystem for absolute paths.
See answers here
It's common to have an images folder within your website's project folder. Put images in this folder, then you can use src="/images/a.jpg"
Is it possible (and a good idea) to pass dynamic data to a JavaScript include file via a hash url?
Such as:
<head> <script src="scripts.js#x=123&y=456"></script> </head>
I am looking for an alternative to inline js in dynamically built pages:
<head>
<script src="scripts.js#x=123&y=456"></script>
<script>
$( document ).ready(function() {
pageInit(123, 456)
});
</script>
</head>
Is it a good idea to avoid inline js? How can you pass dynamic data without ajax which creates a needless roundtrip network request?
Note: The hash bang url is a special because the browsers ignore the hash portion of the url when checking the cache. At least for html files.
So all of these will reuse the index.html file it is in the cache:
index.html
index.html#x=123
index.html#x=345345
index.html#x=2342&y=35435
This same principle should hold true for javascript files. What I hope to achieve is to reuse the cache version of script.js from page to page.
Going to index.php, include this:
<head> <script src="scripts.js#x=123&y=456"></script> </head>
Then going to fun.php include this
<head> <script src="scripts.js#x=898756465&y=5678665468456"></script> </head>
Then going to see.php include this
<head> <script src="scripts.js#session=887987979&csrf_token=87965468796"></script> </head>
From page view to page view, pass whatever info the page needs via the hash bang while at the same time reuse scirpt.js from cache.
So, is it possible to read the hash bang info from within the scirpts.js?
If the HTML file you are creating is dynamic, then just create inline JavaScript. Writing an include will just create an extra request from the browser, which you can avoid in the first place.
Edit:
just include a JavaScript file that reads the URL, you don't need to pass any variables (but of course, you also could):
$(document).ready(function() {
// pseudo code
hashbang = location.href.substr(location.href.indexOf('#') + 1);
if (hashbang.x && hashbang.y) {
pageInit(hashbang.x, hashbang.y);
} else if (hashbang.csrf_token) {
// do something else
}
});
Is there any way that in an external javascript file, can know the host of the file?
For example, if I have the site http://hostOne.com/index.php, the code of the file index.php:
<html>
<head>
<script type="text/javascript" src="http://hostTwo.com/script/test.js"></script>
</head>
<body>
<div>...</div>
</body>
</html>
I need that in the file test.js can know the host http://hostTwo.com.
Thank you.
EDIT
or it can know the tag "script" which was called?, with this option I can analyzes the tag and get the "src" attribute. But I don't want to depend on the name of the file test.js and analyze all the tag script that contains the site.
*Solution based on the code of #Armi *
Html:
<html>
<head>
<script class="jsbin" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>
<script id="idscript" type="text/javascript" src="http://hostTwo.com/script/test.js"></script>
</head>
<body>
<div>...</div>
</body>
</html>
code in JS
var
url = $('head').find('#idscript').attr('src'),
host = url.replace(/(\/\/.*?\/).*/g, '$1');
console.log(host);
I've got an idea (the snippet based on jQuery):
var yourScriptTag = $('head').find('script[src$="jquery-1.7.1.js"]').eq(0);
var theHostnameOfYourScript = $(yourScriptTag).attr('src').replace(/(http:\/\/.*?\/).*/g, '$1');
alert(theHostnameOfYourScript);
jsfiddle example: http://alpha.jsfiddle.net/XsJn8/
If you know the filename of your script (and if this is always the same and unique) you can use this snippet to get the hostname.
If this path is relative (and contains no host) you can get the hostname with a simple location.hostname
Sorry, not possible. The content of the script is downloaded and after this it is fired. At this point the script "thinks" he is at your site.
Of course unless the host is hardcoded in the script.
This is not possible, because the JavaScript code is executed client-sided. You could propably parse it somehow out of your URL but, I don't think either that this is very useful and possible.
Inside test.js, you can use :
var url = document.URL;
then parse the url result.
You can't make cross-site scripting, so if you need more sophisticated stuff, you could write your javascript in php and call :
<script type="text/javascript" src="http://hostTwo.com/script/test.php"></script>
But that's not standard.
Anyway,, the solution is on the server, with a designed proxy.
So I'm running this javascript, and everything works fine, except the paths to the background image. It works on my local ASP.NET Dev environment, but it does NOT work when deployed to a server in a virtual directory.
This is in an external .js file, folder structure is
Site/Content/style.css
Site/Scripts/myjsfile.js
Site/Images/filters_expand.jpg
Site/Images/filters_colapse.jpg
then this is where the js file is included from
Site/Views/ProductList/Index.aspx
$("#toggle").click(function() {
if (left.width() > 0) {
AnimateNav(left, right, 0);
$(this).css("background", "url('../Images/filters_expand.jpg')");
}
else {
AnimateNav(left, right, 170);
$(this).css("background", "url('../Images/filters_collapse.jpg')");
}
});
I've tried using '/Images/filters_collapse.jpg' and that doesn't work either; however, it seems to work on the server if I use '../../Images/filters_collapse.jpg'.
Basically, I want have the same functionallity as the ASP.NET tilda -- ~.
update
Are paths in external .js files relative to the Page they are included in, or the actual location of the .js file?
JavaScript file paths
When in script, paths are relative to displayed page
to make things easier you can print out a simple js declaration like this and using this variable all across your scripts:
Solution, which was employed on StackOverflow around Feb 2010:
<script type="text/javascript">
var imagePath = 'http://sstatic.net/so/img/';
</script>
If you were visiting this page around 2010 you could just have a look at StackOverflow's html source, you could find this badass one-liner [formatted to 3 lines :) ] in the <head /> section
get the location of your javascript file during run time using jQuery by parsing the DOM for the 'src' attribute that referred it:
var jsFileLocation = $('script[src*=example]').attr('src'); // the js file path
jsFileLocation = jsFileLocation.replace('example.js', ''); // the js folder path
(assuming your javascript file is named 'example.js')
A proper solution is using a css class instead of writing src in js file.
For example instead of using:
$(this).css("background", "url('../Images/filters_collapse.jpg')");
use:
$(this).addClass("xxx");
and in a css file that is loaded in the page write:
.xxx {
background-image:url('../Images/filters_collapse.jpg');
}
Good question.
When in a CSS file, URLs will be relative to the CSS file.
When writing properties using JavaScript, URLs should always be relative to the page (the main resource requested).
There is no tilde functionality built-in in JS that I know of. The usual way would be to define a JavaScript variable specifying the base path:
<script type="text/javascript">
directory_root = "http://www.example.com/resources";
</script>
and to reference that root whenever you assign URLs dynamically.
For the MVC4 app I am working on, I put a script element in _Layout.cshtml and created a global variable for the path required, like so:
<body>
<script>
var templatesPath = "#Url.Content("~/Templates/")";
</script>
<div class="page">
<div id="header">
<span id="title">
</span>
</div>
<div id="main">
#RenderBody()
</div>
<div id="footer">
<span></span>
</div>
</div>
I used pekka's pattern.
I think yet another pattern.
<script src="<% = Url.Content("~/Site/Scripts/myjsfile.js") %>?root=<% = Page.ResolveUrl("~/Site/images") %>">
and parsed querystring in myjsfile.js.
Plugins | jQuery Plugins
Please use the following syntax to enjoy the luxury of asp.net tilda ("~") in javascript
<script src=<%=Page.ResolveUrl("~/MasterPages/assets/js/jquery.js")%>></script>
I found this to work for me.
<script> document.write(unescape('%3Cscript src="' + window.location.protocol + "//" +
window.location.host + "/" + 'js/general.js?ver=2"%3E%3C/script%3E'))</script>
between script tags of course... (I'm not sure why the script tags didn't show up in this post)...
You need to add runat="server" and and to assign an ID for it, then specify the absolute path like this:
<script type="text/javascript" runat="server" id="myID" src="~/js/jquery.jqGrid.js"></script>]
From the codebehind, you can change the src programatically using the ID.
This works well in ASP.NET webforms.
Change the script to
<img src="' + imagePath + 'chevron-large-right-grey.gif" alt="'.....
I have a master page for each directory level and this is in the Page_Init event
Dim vPath As String = ResolveUrl("~/Images/")
Dim SB As New StringBuilder
SB.Append("var imagePath = '" & vPath & "'; ")
ScriptManager.RegisterClientScriptBlock(Me, Me.GetType(), "LoadImagePath", SB.ToString, True)
Now regardless of whether the application is run locally or deployed you get the correct full path
http://localhost:57387/Images/chevron-large-left-blue.png