How to detect mixed content with angular?

I have an application angularjsworking on tomcat, and forloadbalancer

If the application is requested through the loadbalancer using https, the balancer still requests the application inside http, of course.

Problem: I would like to hide one tab that displays mixed content in this case (because I need to embed external pdf links that do not support https, so I would like to hide them).

I can’t use $location.protocol(), because the application is behind the balancer and always receives only http.

Question: is there a chance to detect if the browser is really showing mixed content?

+4
source share
1 answer

You cannot discover this in a simple way. You can try to listen to the load event on the iframe and set a timeout, and if the timeout fires, block the iframe because the iframe did not load like this ( jsfiddle example ):

checkMixedContent(urlToCheck, function(urlToCheck) {
    // For example, change location
    alert('ok');
    // load iframe
}, function() {
    alert('Error: resource timed out');
    // hide iframe / show message
}, checkDelay);

function checkMixedContent(urlToCheck, successCallback, errorCallback, checkDelay, dontCheckOnError) {
    checkDelay = checkDelay || 10000;
    // 1. Create invisible iframe and append it to body
    var iframeHelper = document.createElement("iframe");
    iframeHelper.src = urlToCheck;
    iframeHelper.height = 0;
    iframeHelper.width = 0;
    iframeHelper.style.visibility = 'hidden';
    document.body.appendChild(iframeHelper);

    // 2. Set time out and while content on iframeHelper.src should be definitely loaded
    var checkTimeout = window.setTimeout(function() {
        errorCallback(urlToCheck);
    }, checkDelay);

    var onLoad = function() {
        window.clearTimeout(checkTimeout); // if OK - not show error => clearTimeout

        iframeHelper.removeEventListener('load', onLoad);
        iframeHelper.removeEventListener('error', onError);
        document.body.removeChild(iframeHelper);
        successCallback(urlToCheck);
    };

    var onError = function() {
        window.clearTimeout(checkTimeout); // if OK - not show error => clearTimeout

        iframeHelper.removeEventListener('load', onLoad);
        iframeHelper.removeEventListener('error', onError);
        document.body.removeChild(iframeHelper);
        errorCallback(urlToCheck);
    };

    // 3. If everything is fine - "load" should be triggered
    iframeHelper.addEventListener('load', onLoad);


    // Turn "true" in case of "X-Frame-Options: SAMEORIGIN"
    if (!dontCheckOnError) {
        iframeHelper.addEventListener('error', onError);
    }

}
0
source

All Articles