Determine protocol used to load javascript
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开发者_StackOverflow 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.
精彩评论