Secure/Non-secure browsing issue - javascript

I am developing a Facebook app that incorporates our Brightcove (video host) players and their API. Facebook gives users the option to browse securely and this poses a little bit of a problem. As is stands, I can get the app to work properly on one of the protocols (http or https), but not both.
https://www.facebook.com/atlantafalcons?sk=app_292392080815275 (change to http:// to see it not working)
If I set the BrightcoveExperiences.js file source to https://sadmin.brightcove.com/js/BrightcoveExperiences.js then it throws errors when someone is not browsing securely. If I set it to http://admin.brightcove.com/js/BrightcoveExperiences.js then it throws errors when someone is browsing securely.
The documentation for embedding securely is here: http://support.brightcove.com/en/docs/publishing-brightcove-player-https-page
Is there a way to detect if the user is browsing securely to be able to choose which JS file to load or is there a way to force users to browse securely? Or is there another workaround for a problem like this?
Thanks in advance!
EDIT:
Was able to come up with a solution (thanks to scibuff for recommending to check google analytics):
<script type="text/javascript">
var bJsHost = (("https:" == document.location.protocol ) ? "https://sadmin." : "http://admin.");
document.write(unescape("%3Cscript src='" + bJsHost + "brightcove.com/js/BrightcoveExperiences.js' type='text/javascript'%3E%3C/script%3E"));
</script>

Use a scheme-relative URI:
//admin.brightcove.com/js/BrightcoveExperiences.js
And don't use different hostnames for the SSL and non-SSL instances.
(Or have sadmin respond with a 301 redirect to admin for non-SSL requests)

I would go with Quentin's suggestion. Although, using your suggestion, you can use:
// window, top, self, document, others?
window.location.protocol
In other words:
if (window.location.protocol == 'http:') {
document.body.innerHTML = 'The page is using the http (non-secure) protocol.';
} else {
document.body.innerHTML = 'The page is using the https (secure) protocol.';
}
http://jsfiddle.net/3NREg/
Other window/document objects might work as well, depending on what you need:
// window, top, self, document, others?
if (self.location.protocol == 'http:') {
document.body.innerHTML = 'The page is using the http (non-secure) protocol.';
} else {
document.body.innerHTML = 'The page is using the https (secure) protocol.';
}
http://jsfiddle.net/3NREg/1/

Related

How to use JavaScript or/and PHP, to detect a website/page being stolen/cloned and then redirect reader back to my website

I found hundreds of cloned versions of my website.
Whoever is doing that are using some code that clones my web pages, changes my website name mydomain.com to clone1.com, clone2.com, clone3.com etc and this makes it impossible to use a simple JS or PHP to check if the header URL is = to mysite.com then redirect.
It also does not work using the .htaccess
For this reason I have created this code:
<script type="text/javascript">
if (window.location.href== "http://clone1.com/cat1/{{{ $title->id }}}-{{ (Str::slug($title->title)) }}/cat2/{{ $se->n }}/cat3/{{ $episode->ep_n }}")
{
window.location.href = 'http://google.com/';
}
</script>
This script completes its purpose but is too long and is also very restrictive because it must contain the exact URL.
I'm looking to do this:
<script type="text/javascript">
if (window.location.href== "http://
//contains this part in its URL
clone1.com , clone2.com , clone3.com , clone4....
}}")
{
window.location.href = 'http://google.com/';
}
</script>
How can I create a global JS (JavaScript), that would detect if the current page is not on my domain and then redirect the reader to my domain and the same page?
Many thanks
1. Best Solution - Early Detection
Depending on your main traffic source, it is possible to detect who is scrapping you and block them based on their IP, Headers, number of page views and other data, using PHP & HTACCESS.
I really like this answer on the StackOverflow, that discusses almost all the options available for early detection.
How to detect fake users ( crawlers ) and cURL
2. Plugins & Extensions for Open Source Content Management Systems
Wordpress
If using Wordpress CMS, you can try some plugins, like WordFence, that can detect and block fake Google Crawlers, block based on the number of page views etc.
Other CMS
If you can't find a similar solution for your CMS of choice, consider to ask a community for a help with creating the solution like that, as I believe many people could benefit from it.
3. Solution for already stolen content with JavaScript
Sometimes the easiest road to hide something in JS, is to actually HIDE something by OBFUSCATING and by hiding in multiple important files. For example, obfuscate some important file on your website without which the website just wouldn't work properly.
For example, put an obfuscated version of the code below somewhere in JS file in the header, Obfuscate this code using any free services online or download your own library on Github:
Non-Obfuscated:
w='mysite.com'; // Current URL e.g. 'mysite.com/category1/page2/'
function check_origin(){
var check = 587;
if(window.location.hostname != w){
window.location.href = w;
}
return check;
}
var check = check_origin();
Obfuscated example:
var _0x303e=["\x6D\x79\x73\x69\x74\x65\x2E\x63\x6F\x6D","\x68\x6F\x73\x74\x6E\x61\x6D\x65","\x6C\x6F\x63\x61\x74\x69\x6F\x6E","\x68\x72\x65\x66"];w= _0x303e[0];function check_origin(){var check=587;if(window[_0x303e[2]][_0x303e[1]]!= w){window[_0x303e[2]][_0x303e[3]]= w};return check}var check=check_origin()
Now put an additional code in some Footer JS File, to verify the code above wasn't modified in any way:
Non-Obfuscated example:
if(w!=='mysite.com'||check == false || typeof check == 'undefined' || check !== 587 ){
window.location.href = 'mysite.com';
}
Obfuscated:
var _0x92bb=["\x6D\x79\x73\x69\x74\x65\x2E\x63\x6F\x6D","\x75\x6E\x64\x65\x66\x69\x6E\x65\x64","\x68\x72\x65\x66","\x6C\x6F\x63\x61\x74\x69\x6F\x6E"];if(w!== _0x92bb[0]|| check== false|| typeof check== _0x92bb[1]|| check!== 587){window[_0x92bb[3]][_0x92bb[2]]= _0x92bb[0]}
I have used free online service from Google's search results for the term "Free Online JS Obfuscator:
https://javascriptobfuscator.com/Javascript-Obfuscator.aspx
4. Fight thieves with available methods e.g. Request a Ban from Search Engines – The Digital Millennium Copyright Act of 1998
Here is a blog-post that describes what to do when someone is stealing your content.
https://lorelle.wordpress.com/2006/04/10/what-do-you-do-when-someone-steals-your-content/
You can investigate who is doing that and report them to their partners, search engines, advertisers - to disrupt their business.
Depending on their country of origin and yours, it is maybe even possible to sue them and win.
why not check if hostname is your ?
if(window.location.hostname != 'mysite.com'){
window.location.href = 'http://google.com/';
}

Jquery.get not working with ssl

I recently added an SSL certificate to my website and since then some of the jquery functions are no longer working. Specifically jquery.get
Example:
function getBfeForm() {
jQuery.get('/wp-admin/admin.php/?page=booking.multiuser.5.3/wpdev-booking.phpwpdev-booking-resources&tab=availability&wpdev_edit_avalaibility=<?php echo key($_REQUEST['avail']); ?>/', function(data) {
jQuery('[name="avail['+<?php echo key($_REQUEST['avail']); ?>+']"]').removeClass('spinner').val('Edit Availability');
if (data) {
jQuery('#availHolder .holder').html(jQuery(data).find('.inside'));
jQuery('#availHolder .holder').prepend('<div id="popHeader"><a title="Close" class="fancybox-item fancybox-close" href="javascript:;">Close</a></div>');
jQuery('#availHolder').hide();
jQuery('#availHolder').appendTo(jQuery('[data-resource="<?php echo key($_REQUEST['avail']); ?>"]').find('tr.clean td'));
jQuery('#availHolder').slideDown(500);
}
});
}
This function works fine with http but when SSL is activated and https used the function no longer calls the file. I have seen other comments on here saying the lack of trailing slashes is the issue, but I believe I have added trailing slashes correctly now and it still doesn't work.
Any help would be greatly appreciated.
UPDATE: I added alert("Data: " + data + "\nStatus: " + status); to the function to see what data was actually being served. It appears the wordpress log in page is being called rather than the file specified in the function. I have tested this on a duplicate site without SSL and it calls the correct file. Does this mean the SSL is not allowing a link to wp-admin files?
If you are using windows and have a local certificate installed in IIS then try access the site with fully qualified name of the computer
[computer_name].[domain_name]
For example: [ox-pchris11].[companyname.com] where ox-pchris11 is the computer name and companyname.com is the domain name.
if you access the site as localhost it will show a error page which will ask permission to continue.
I found the problem and posting the answer here for anyone else who is implementing an SSL certificate. The issue was the custom login page we have. We are using the wp_signon function and we had $user_verify = wp_signon( $login_data, false );. This should be $user_verify = wp_signon( $login_data, true ); - setting the value to 'true' creates a secure cookie. If the cookie is not secure, each time a user tries to access wp-admin files they are logged out and required to log in again.
For details check the wordpress codex for wp_signon.

online offline check using javascript [duplicate]

This question already has answers here:
Detect the Internet connection is offline?
(22 answers)
Closed 8 years ago.
How do you check if there is an internet connection using jQuery? That way I could have some conditionals saying "use the google cached version of JQuery during production, use either that or a local version during development, depending on the internet connection".
The best option for your specific case might be:
Right before your close </body> tag:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script>window.jQuery || document.write('<script src="js/vendor/jquery-1.10.2.min.js"><\/script>')</script>
This is probably the easiest way given that your issue is centered around jQuery.
If you wanted a more robust solution you could try:
var online = navigator.onLine;
Read more about the W3C's spec on offline web apps, however be aware that this will work best in modern web browsers, doing so with older web browsers may not work as expected, or at all.
Alternatively, an XHR request to your own server isn't that bad of a method for testing your connectivity. Considering one of the other answers state that there are too many points of failure for an XHR, if your XHR is flawed when establishing it's connection then it'll also be flawed during routine use anyhow. If your site is unreachable for any reason, then your other services running on the same servers will likely be unreachable also. That decision is up to you.
I wouldn't recommend making an XHR request to someone else's service, even google.com for that matter. Make the request to your server, or not at all.
What does it mean to be "online"?
There seems to be some confusion around what being "online" means. Consider that the internet is a bunch of networks, however sometimes you're on a VPN, without access to the internet "at-large" or the world wide web. Often companies have their own networks which have limited connectivity to other external networks, therefore you could be considered "online". Being online only entails that you are connected to a network, not the availability nor reachability of the services you are trying to connect to.
To determine if a host is reachable from your network, you could do this:
function hostReachable() {
// Handle IE and more capable browsers
var xhr = new ( window.ActiveXObject || XMLHttpRequest )( "Microsoft.XMLHTTP" );
// Open new request as a HEAD to the root hostname with a random param to bust the cache
xhr.open( "HEAD", "//" + window.location.hostname + "/?rand=" + Math.floor((1 + Math.random()) * 0x10000), false );
// Issue request and handle response
try {
xhr.send();
return ( xhr.status >= 200 && (xhr.status < 300 || xhr.status === 304) );
} catch (error) {
return false;
}
}
You can also find the Gist for that here: https://gist.github.com/jpsilvashy/5725579
Details on local implementation
Some people have commented, "I'm always being returned false". That's because you're probably testing it out on your local server. Whatever server you're making the request to, you'll need to be able to respond to the HEAD request, that of course can be changed to a GET if you want.
Ok, maybe a bit late in the game but what about checking with an online image?
I mean, the OP needs to know if he needs to grab the Google CMD or the local JQ copy, but that doesn't mean the browser can't read Javascript no matter what, right?
<script>
function doConnectFunction() {
// Grab the GOOGLE CMD
}
function doNotConnectFunction() {
// Grab the LOCAL JQ
}
var i = new Image();
i.onload = doConnectFunction;
i.onerror = doNotConnectFunction;
// CHANGE IMAGE URL TO ANY IMAGE YOU KNOW IS LIVE
i.src = 'http://gfx2.hotmail.com/mail/uxp/w4/m4/pr014/h/s7.png?d=' + escape(Date());
// escape(Date()) is necessary to override possibility of image coming from cache
</script>
Just my 2 cents
5 years later-version:
Today, there are JS libraries for you, if you don't want to get into the nitty gritty of the different methods described on this page.
On of these is https://github.com/hubspot/offline. It checks for the connectivity of a pre-defined URI, by default your favicon. It automatically detects when the user's connectivity has been reestablished and provides neat events like up and down, which you can bind to in order to update your UI.
You can mimic the Ping command.
Use Ajax to request a timestamp to your own server, define a timer using setTimeout to 5 seconds, if theres no response it try again.
If there's no response in 4 attempts, you can suppose that internet is down.
So you can check using this routine in regular intervals like 1 or 3 minutes.
That seems a good and clean solution for me.
You can try by sending XHR Requests a few times, and then if you get errors it means there's a problem with the internet connection.
I wrote a jQuery plugin for doing this. By default it checks the current URL (because that's already loaded once from the Web) or you can specify a URL to use as an argument. Always doing a request to Google isn't the best idea because it's blocked in different countries at different times. Also you might be at the mercy of what the connection across a particular ocean/weather front/political climate might be like that day.
http://tomriley.net/blog/archives/111
i have a solution who work here to check if internet connection exist :
$.ajax({
url: "http://www.google.com",
context: document.body,
error: function(jqXHR, exception) {
alert('Offline')
},
success: function() {
alert('Online')
}
})
Sending XHR requests is bad because it could fail if that particular server is down. Instead, use googles API library to load their cached version(s) of jQuery.
You can use googles API to perform a callback after loading jQuery, and this will check if jQuery was loaded successfully. Something like the code below should work:
<script type="text/javascript">
google.load("jquery");
// Call this function when the page has been loaded
function test_connection() {
if($){
//jQuery WAS loaded.
} else {
//jQuery failed to load. Grab the local copy.
}
}
google.setOnLoadCallback(test_connection);
</script>
The google API documentation can be found here.
A much simpler solution:
<script language="javascript" src="http://maps.google.com/maps/api/js?v=3.2&sensor=false"></script>
and later in the code:
var online;
// check whether this function works (online only)
try {
var x = google.maps.MapTypeId.TERRAIN;
online = true;
} catch (e) {
online = false;
}
console.log(online);
When not online the google script will not be loaded thus resulting in an error where an exception will be thrown.

Javascript Get Website URL

How do I get Javascript to tell me the website url.
For example if I have a page www.example.com/page.html
I want Javascript to tell me the site url is www.example.com and not www.example.com/page.html (which document.location tells me)
Is there a way to do this? If so, how?
Thanks in advance for your help :)
There are several ways you can do this, but one way might be best for certain situations (e.g. within an iFrame).
Protocol + Domain + Page
document.URL
> "http://example.com/page1.html"
document.location.href
> "http://example.com/page1.html"
Protocol + Domain
document.location.origin
> "http://example.com"
Domain
document.location.host
> "example.com"
Page
document.location.pathname
> "/page1.html"
There are many ways to get this.
Open Chrome browser and press F12, you'll get console.
Type following commands there for the same question URL. You will get your answer
window.location.hostname // Output : stackoverflow.com
window.location.origin // Output : http://stackoverflow.com
document.location.host // Output : stackoverflow.com
Use
window.location.hostname
You can test it by just typing it in the chrome dev tools console
Reference
MDN: https://developer.mozilla.org/en-US/docs/Web/API/Location
use
document.location.origin+document.location.pathname;
where document.location.origin will redirect you to "http://www"
and document.location.pathname will redirect you to "/stackoverflow/"(Name of your project).
In this way you can give reference to page or post you want in your js file.Suppose if i want reference to my home page i would have use
var address=document.location.origin+document.location.pathname;
window.location.replace(address+"/home");
So using above example i can easily redirect to my homepage
Try this
document.location.host
Use alert(window.location.origin) for getting the url.
Try
document.location.origin
That will give you the protocol and host.
you can also use location.href = '/' + 'path_name/sub_path_name'
'/' = takes you to the home page then
'path_name/sub_path_name' = to pass the new path to the domain page

Unsafe JavaScript attempt to access frame...Protocols must match

Here's my situation: I have a Javascript plugin that when clicked launches a popup on the third-party sites that host it. That popop then displays an IFRAME, in which I am using Facebook as a login method.
When the popup is launched, it recently started giving an error:
Unsafe JavaScript attempt to access frame with URL
http://{THIRD-PARTY-SITE-GOES-HERE} from frame with URL
https://s-static.ak.facebook.com/connect/xd_arbiter.php?version=18#channel=…%3Dtabmodule%26utm_term%3D200000%26fb_xd_fragment%23xd_sig%3Df2ade8e518%26.
The frame requesting access has a protocol of 'https', the frame being
accessed has a protocol of 'http'. Protocols must match.
The IFRAME itself is on https and used to work properly. I'm not sure why Chrome is trying to access the parent page. I have no control over the parent pages, so I can't make them https.
Here is my FB init code from within the IFRAME:
window.fbAsyncInit = function()
{
FB.init({
appId: '{myappid}',
status: true,
cookie: true,
xfbml: true,
oauth: true,
channelURL : 'https://degree3.com/channel.php'
});
FB.getLoginStatus( function(response)
{
if (resp = response.authResponse)
{
$( '#fb_button' ).attr( "onclick", "signinViaFacebook( response.authResponse.userID, response.authResponse.accessToken );" ).show();
}
});
};
(function()
{
var e = document.createElement('script'); e.async = true;
e.src = document.location.protocol + '//connect.facebook.net/en_US/all.js';
document.getElementById('fb-root').appendChild(e);
}());
Any ideas how I can fix the error?
You can't use facebook login inside an iframe it will never work. Dont even bother trying I have spent several frustrating hours trying to do the same. Even if you solve the https problem you have right now, you will then face an X-Frame Options error because of an option set in the response header by facebook which accepts only requests from same origin(that is facebook).
What I'am basically trying to say is that facebook cannot be launched in an Iframe for security reasons. Your best bet in your current predicament is to open another popup with facebook login in it. Iframe simply wouldn't work. I know it wouldn't look elegant but it is the only way to go or you redirect your popup itself to facebook and have a callback mechanism to redirect back to your plugin.
Hope it helps.

Categories

Resources