I have javascript file, located on one domain, e.g:
http://mydomain.com/script.js
Some pages (from other domains) include my javascript using SCRIPT tag. They can include it via http or https
<script src="http://mydomain.com/script.js"></script>
or
<script src="https://mydomain.com/script.js"></script>
Also they can include my script using 3rdparty iframes, e.g:
<iframe src="http://3rdparty.com/frame.php">
where http://3rdparty.com/frame.php outputs
<script src="http://mydomain.com/script.js"></script>
or
<script src="https://mydomain.com/script.js"></script>
I can edit only static javascript file script.js on mydomain.com.
How I can detect what protocol used to load my javascript (https://mydomain.com/script.js or http://mydomain.com/script.js)?
You can use a protocol relative URL:
<script src="//mydomain.com/script.js"></script>
You can use this:
document.location.protocol + "//mydomain.com/script.js"
I do not believe that you have any ability to identify within the code how it has been loaded. The best suggestion I can come up with is to have the http and https point to different locations ( i.e. be different sites ) and have something within the code that indicates which one is being picked up.
var protocol='http'
or
var protocol='https'
It does mean maintaining two files, and two sites though.
ETA: I thought James Wiseman had the answer, but of course that will only return the protocol of the PAGE, not the SCRIPT. If you know these are related, that would work ( often the https is loaded on https pages and vv ). But it is not definitive.
It is a good solution if you can be confident that the protocol on hte page is the same as on the script.
Related
I use a library on my main site www.domain.com as such
<script src = 'lib.js'>
However, when I link out to another tab that points to ( using target = '_blank' )
www.domain.com/path
the library is gone and I have to reload it.
Is this expected behavior?
I thought because resources like localStroage have limits based on domain that other aspects of the environment would be domain based.
That is resources I load at www.domain.com I thought would be available at www.domain.com/path.
But this seems to not be the case.
Javascript files are only loaded for one page and need to be loaded again for every other page regardless of the domain or path.
I know this is a duplicate question however my requirements are slightly different,
In a previous question this was tackled by setting:
document.domain = "yourdomain.com";
on both pages.
However... I have a www.example.com domain and I have a mail.example.com
the mail.example.com is a subdomain I have no access to, it is automatically generated by my shared hosting and its where i access my emails. However I want an iframe with mail.example.com as the source on one of my pages.
e.g.
// www.example.com/mail.php
<html>
<head>...</head>
<body>
...
<? include("header.php"); ?>
...
<iframe src="mail.example.com"></iframe>
...
</body>
</html>
This works as expected but certain styles are applied to the iframe, so i want to use javascript to remove all the styles, then add my own.
But because i dont have access to mail.example.com, i cant set document.domain = "example.com"; in the sub domain.
Is there another way round this?
EDIT
I didn't make it very clear what I had already tried.
This is my exact iframe code in my mail.php page on the www.example.com domain:
<iframe id="mail" src="http://mail.a3mediauk.co.uk/mail2/source/index.php" height="800" width="960"></iframe>
This is the javascript code thats at the very top of the head element in the mail.php page:
document.domain = "http://mail.a3mediauk.co.uk";
And this is the jquery code im trying to use to remove the style:
$(function(){
$("iframe#mail").load(function(){
$("iframe#mail body").removeAttr("bgcolor");
});
});
if its any help, the document.domain throws this error in the chrome console:
Uncaught Error: SECURITY_ERR: DOM Exception 18
You probably forgot the http://
An iFrame is client-sided (HTML) so you have to enter the absolute path because it is a different domain. What you have written would redirect to http://yourdomain.com/mail.yourdomain.com.
As far as the same origin policy is concerned, the URLs have to match exactly. It doesn't matter if one is a subdomain of the other; the strings are different, so you're violating the policy.
I don't see a good solution. If the page was simple (no or only simple JavaScript, no links, etc), you can try to fetch the mail page with JavaScript into a String, strip the header (i.e. convert the body into a div) and then add that to your main page. But of course, this would break all links, the referrer, and cause lots of other problems like, say, what happens if a new version of the mail interface is installed?
Another solution would be to install a proxy service which makes everything from mail.domain.com available as your.domain.com/mail. If you run Apache on your domain, a simple rewrite rule using the "Proxy Throughput" feature should do the trick.
I'm developing a small application with HTML, CSS, Javascript, JQuery and JQTouch.
This is a LOCAL application. I've an index.html with some div's. When I click on a link in this file, I want to load HTML code of page1.html (same folder) and insert into a div of index.html the tag that I want of page1.html.
Example: Inject the content of (page1.html) into (index.html).
I try: http://api.jquery.com/load/
$('#loadContent').load('page1.html #test');
And the content of loadContent doesn't change. I include JQuery script into index.html...
I try http://api.jquery.com/html/ too, but I think it connect to the server.
Any idea? Thanks!
Make sure you're calling it after loadContent has been created. The following will run your load code when the document is ready to be written to.
$(function() {
$('#loadContent').load('page1.html #test');
});
Or you could run a local server. If you have python you can go to your directory with the files and run python -m SimpleHTTPServer for python 2.7 or python -m http.server for python 3.x
Most browsers will, by default, block this on a local file system as a security precaution. Have you tried it on a remote server?
I dont know much on jQuery. But still, you can do this, by loading the page1.html to a hidden iframe, then get the document.body.innerHTML of this page, and then append that node to the div you need. Its only HTML DOM in JavaScript.
But performance base, loading an iframe is always a costly one. This would do your job. However there may be many solutions in jQuery or other libraries, Sorry i don't know much on it.
It sounds like the problem is that the jQuery library isn't loading when you're running on localhost, or the AJAX request is failing for the same reason. This is due to protection built into the browser to prevent cross-site scripting.
See this "additional note" from the documentation for load:
Due to browser security restrictions, most "Ajax" requests are subject to the same origin policy; the request can not successfully retrieve data from a different domain, subdomain, or protocol.
If you use any AJAX, you'll have to run this on a local web server. In which case you should just run this page from your local webserver rather than from the filesystem. Then you won't need any workarounds.
If you're on Windows, you could use UniServer.
If you aren't going to use any AJAX whatsoever (aren't using load), then you could write your code so that it falls back to a local version of jQuery if the remote version didn't load.
Here's an example of how, grabbed from this page:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
<script>!window.jQuery && document.write('<script src="/Scripts/lib/jquery/jquery-1.4.4.min.js"></script>'))</script>
<script src="//ajax.aspnetcdn.com/ajax/jquery.validate/1.7/jquery.validate.min.js"></script>
<script>!window.jQuery.validator && document.write('<script src="/Scripts/lib/jquery/jquery.validate.min.js"></script>')</script>
<script src="//ajax.aspnetcdn.com/ajax/mvc/3.0/jquery.validate.unobtrusive.min.js"></script>
<script>!window.jQuery.validator.unobtrusive && document.write('<script src="/Scripts/lib/jquery/jquery.validate.unobtrusive.min.js"></script>')</script>
Is it possible for me to supply a client with a snippet of HTML which contains a reference to a javascript file that I host? They want to paste this HTML into their CMS, so that when their page loads, it'll load our content.
I was under the impression that there was cross domain security preventing this from being possible.
What if, instead of linking to the JavaScript, I gave them the snippet of HTML with the JavaScript already included
so instead of
<div>
<!-- link to js -->
</div>
I gave them
<div>
$.get(/*url to my content*/);
</div>
Would that work?
You could use JSONP to simulate cross domain AJAX calls (works only with GET requests as internally it uses a script tag):
$.getJSON("http://api.flickr.com/services/feeds/photos_public.gne?tags=cat&tagmode=any&format=json&jsoncallback=?",
function(data) {
$.each(data.items, function(i,item) {
$("<img/>").attr("src", item.media.m).appendTo("#images");
if ( i == 3 ) return false;
});
}
);
Is it possible for me to supply a client with a snippet of HTML which contains a reference to a javascript file that I host?
Yes. The src of script elements has no same origin limits.
$.get(/*url to my content*/);
XMLHttpRequests still do have same origin limits. XHR can only fetch from the domain of the page, not the script.
The HTML <script> tags are exempt from the same origin policy, so if your client links to your JavaScript file with <script> tags, you will not have any problems. (Source)
Referencing a javascript file from a different domain is no problem. This is not cross site scripting, it's simply a cross site HTTP request. This is used a lot, e.g. by Google's JavaScript API Loader.
Previously, Google's Friend Connect required users to upload a couple of files to their websites to enable cross domain communication and Facebook Connect still requires you to upload a single file to enabled it.
Now, Friend Connect doesn't require any file upload... I was wondering how they were able to accomplish this.
Reference:
http://www.techcrunch.com/2009/10/02/easy-does-it-google-friend-connect-one-ups-facebook-connects-install-wizard/
There are multiple methods of communicating between documents on different domains, amongst these HTML5 postMessage, NIX, FIM(hash/fragment), frameElement and by using the window.name property.
These are available on different browsers and in different versions, but collectively they allow you to do reliable XDM (cross domain messaging).
One project that have done this earlier is Apache Shindig, which probably pioneered quite a few of these, and more recently, the project easyXDM has come, unifying all of these approaches with a common API, making it easy to create complex applications using XDM and RPC.
You can read in depth about the various methods of transporting the data in this article at Script Junkie.
Now, to answer your question directly, earlier on it was quite common to believe that there was only postMessage, the FIM (Fragment Identifier Messaging) available, and for the latter to work efficiently, one often had to upload a special file to your domain. As more methods have been discovered, this has by many been deprecated as a technique, and hence; no more need for the file.
Just for the record; I'm the author of both the Script Junkie article, and the easyXDM library (that is what Twitter, Disqus and quite a few more are using by the way).
<edit>It's difficult to remember/verify now, but I believe my answer here was probably incorrect. Sean Kinsey's answer above should be the definitive answer to this question. If you're reading this, please upvote his answer and ignore mine.</edit>
The Google Friend Connect widget works like most ads/gadgets do, using a copy/pasted snippet of HTML to reference a JavaScript include on the host's server which then creates an iframe containing the desired content. By opening the iframe with your site ID in the URL, Google's server is able to generate the appropriate HTML document to represent a Friend Connect gadget for your particular site/settings.
There isn't any cross-site communication happening beyond that initial step of creating an iframe with the appropriate URL target. Everything inside the gadget's dynamically generated iframe is more like the user visited a separate page on Google's server, but what would have been displayed is then embedded/isolated in a block on your page instead.
I'm not sure how it works in this particular instance but cross-domain messaging can be accomplished either by the postMessage() API or by changing the hash part of the URL and monitoring that.
The hash change method works because both the enclosing and the enclosed pages have access to the enclosed page's URL.
Of course, hopefully the postMessage() API call becomes more standard over time.
JSON allows cross-domain javascript.
Due to browser security restrictions,
most "Ajax" requests are subject to
the same origin policy; the request
can not successfully retrieve data
from a different domain, subdomain,
or protocol.
Script and JSONP
requests are not subject to the same
origin policy restrictions.
There is no other method than using the somewindow.postMessage(); for communication between cross-domain iframes.
Before somewindow.postMessage() you had to upload file in order to ensure that you can establish communication between iframes.
example:
<html>
<!-- this is main domain www.example.com -->
<head>
</head>
<body>
<iframe src="http://www.exampleotherdomain.com/">
<script>
function sendMsg(a) {
var f = document.createElement('iframe'),
k = document.getElementById('ifr');
f.setAttribute('src', 'http://www.example.com/xdreciver.html#myValueisSent');
k.appendChild(f);
k.removeChild(f);
}
</script>
<div id="ifr"></div>
</iframe>
</body>
</html>
now the http://www.example.com/xdreciver.html html content :
<html>
<!-- this is http://www.example.com/xdreciver.html -->
<head>
<script>
function getMsg() {
return window.location.hash;
}
</script>
</head>
<body onload="var msg = getMsg(); alert(msg);">
</body>
</html>
As for using the .postMessage(); its enough to use top.postMessage('my message to other domain document, which is also the main document', 'http://www.theotherdomain.com');