Iframe http error

I have an that other sites can include so their users can POST a form back to my site. I'd like to handle gracefully the cases where my site is down or my server can't serve the <...

I have an <iframe> that other sites can include so their users can POST a form back to my site. I’d like to handle gracefully the cases where my site is down or my server can’t serve the <iframe> contents (that is, a response timeout or a 4xx or 5xx error). I tried adding an onError to the <iframe> object, but that didn’t seem to do anything:

showIFrame = function() {
  var iframe = document.createElement('iframe');
  iframe.id = 'myIFrame';
  iframe.src = 'http://myserver.com/someURLThatFailsToLoad';
  iframe.onError = iframe.onerror = myHandler;
  document.body.appendChild(iframe);
};

myHandler = function(error) {
  document.getElementById('myIFrame').style.display = 'none';
  console.error('Error loading iframe contents: ' + error);
  return true;
};

If my server returns a 404 I just get the contents of the not-found page in my <iframe>. In fact, that error handler isn’t ever triggered. Is there a way to make this work?

(I’m currently testing in Chrome, but I’d like it to also work for FF and IE >= 7.)

asked Sep 13, 2010 at 23:11

James A. Rosen's user avatar

James A. RosenJames A. Rosen

63.5k61 gold badges178 silver badges261 bronze badges

To detect whether your server is down or not, you can include an empty script file from your own domain. When the server is down, the onerror event handler will fire:

var el = document.createElement('script');
el.onerror = errorFunction;
el.src = "somebogusscript.js?" + new Date().getTime();
document.body.appendChild(el);

Note: don’t forget to add a random string to the src attribute to avoid the client using a cached version (which could stop a look at the server at all).

answered Sep 13, 2010 at 23:17

Marcel Korpel's user avatar

Marcel KorpelMarcel Korpel

21.5k6 gold badges60 silver badges80 bronze badges

5

One technique is to set a JavaScript timeout when you make the request. If your timeout fires before the iframe onload event, the content didn’t load. You could then set iframe.src to about:blank, delete, or reuse the iframe.

answered Mar 29, 2012 at 8:51

Sam Watkins's user avatar

Sam WatkinsSam Watkins

7,6413 gold badges38 silver badges38 bronze badges

I am using Knockout.js to bind iframe src tag(This will be configurable with respect to User).

Now, if user has configured http://www.google.com (I know it won’t load in iframe, thats why I am using it for -ve scenario) and that has to be shown in IFrame.
but it throws error:-

Refused to display ‘http://www.google.co.in/’ in a frame because it
set ‘X-Frame-Options’ to ‘SAMEORIGIN’.

I have the following code for Iframe:-

<iframe class="iframe" id="iframe" data-bind="attr: {src: externalAppUrl, height: iframeheight}">
    <p>Hi, This website does not supports IFrame</p>
</iframe>

What I want is, if the URL fails to load. I want to display Custom Message.
Screenshot of console when I get error
FIDDLE HERE

Now, if I use onload and onerror as:-

<iframe id="browse" style="width:100%;height:100%" onload="alert('Done')" onerror="alert('Failed')"></iframe>

It works fine loading w3schools.com but not with google.com.

Secondly:- if I make it as a function and try like I have done in my fiddle, it doesn’t works.

<iframe id="browse" style="width:100%;height:100%" onload="load" onerror="error"></iframe>

I don’t know how should I make it run and capture the error.

Edited:- I have seen Want to call a function if iframe doesn’t load or load’s question in stackoverflow but it shows error for sites that can be loaded in iframe.

Also, I have looked into Stackoverflow iframe on load event
Thanks!!

j.doe's user avatar

j.doe

6624 silver badges18 bronze badges

asked Mar 7, 2013 at 13:56

Shubh's user avatar

0

You wont be able to do this from the client side because of the Same Origin Policy set by the browsers. You wont be able to get much information from the iFrame other than basic properties like its width and height.

Also, google sets in its response header an ‘X-Frame-Options’ of SAMEORIGIN.

Even if you did an ajax call to google you wont be able to inspect the response because the browser enforcing Same Origin Policy.

So, the only option is to make the request from your server to see if you can display the site in your IFrame.

So, on your server.. your web app would make a request to www.google.com and then inspect the response to see if it has a header argument of X-Frame-Options. If it does exist then you know the IFrame will error.

answered Sep 6, 2013 at 19:47

Evan Larsen's user avatar

Evan LarsenEvan Larsen

9,8754 gold badges47 silver badges60 bronze badges

6

I think that you can bind the load event of the iframe, the event fires when the iframe content is fully loaded.

At the same time you can start a setTimeout, if the iFrame is loaded clear the timeout alternatively let the timeout fire.

Code:

var iframeError;

function change() {
    var url = $("#addr").val();
    $("#browse").attr("src", url);
    iframeError = setTimeout(error, 5000);
}

function load(e) {
    alert(e);
}

function error() {
    alert('error');
}

$(document).ready(function () {
    $('#browse').on('load', (function () {
        load('ok');
        clearTimeout(iframeError);
    }));

});

Demo: http://jsfiddle.net/IrvinDominin/QXc6P/

Second problem

It is because you miss the parens in the inline function call; try change this:

<iframe id="browse" style="width:100%;height:100%" onload="load" onerror="error"></iframe>

into this:

<iframe id="browse" style="width:100%;height:100%" onload="load('Done func');" onerror="error('failed function');"></iframe>

Demo: http://jsfiddle.net/IrvinDominin/ALBXR/4/

coolaj86's user avatar

coolaj86

72k19 gold badges102 silver badges121 bronze badges

answered Aug 31, 2013 at 20:57

Irvin Dominin's user avatar

Irvin DomininIrvin Dominin

30.7k9 gold badges80 silver badges110 bronze badges

10

The onload will always be trigger, i slove this problem use try catch block.It will throw an exception when you try to get the contentDocument.

iframe.onload = function(){
   var that = $(this)[0];
   try{
        that.contentDocument;
   }
   catch(err){
        //TODO 
   }
}

answered Aug 4, 2017 at 11:05

H.Eden's user avatar

H.EdenH.Eden

1571 silver badge8 bronze badges

5

This is a slight modification to Edens answer — which for me in chrome didn’t catch the error. Although you’ll still get an error in the console:
«Refused to display ‘https://www.google.ca/’ in a frame because it set ‘X-Frame-Options’ to ‘sameorigin’.» At least this will catch the error message and then you can deal with it.

 <iframe id="myframe" src="https://google.ca"></iframe>

 <script>
 myframe.onload = function(){
 var that = document.getElementById('myframe');

 try{
    (that.contentWindow||that.contentDocument).location.href;
 }
 catch(err){
    //err:SecurityError: Blocked a frame with origin "http://*********" from accessing a cross-origin frame.
    console.log('err:'+err);
}
}
</script>

answered Sep 22, 2018 at 16:32

user2677034's user avatar

user2677034user2677034

59410 silver badges20 bronze badges

1

I solved it with window.length.
But with this solution you can take current error (X-Frame or 404).

iframe.onload = event => {
   const isLoaded = event.target.contentWindow.window.length // 0 or 1
}

MSDN

Regolith's user avatar

Regolith

2,9269 gold badges33 silver badges50 bronze badges

answered Aug 14, 2019 at 9:41

Qeemerc's user avatar

QeemercQeemerc

791 silver badge1 bronze badge

0

Update:
contentWindow.name will now always throw an error on cross-origin frames.
Seems like the only way is to do this server side (for now).
I have written a small cloudflare worker to capture headers for remote apis and it can be used here to check for X-Frame-Options.

Sample code to check before rendering in iframe: (jsfiddle: https://jsfiddle.net/2gud39aw/2/)

function checkUrlFrameOptions(apiurl){
  return fetch("https://header-inspector.repalash.workers.dev/?" + new URLSearchParams({
    'apiurl': apiurl,
    'headers': 'x-frame-options'
  }), {
    method: 'GET'
  }).then(r => r.json()).then(json => {
    let xFrameOp = (json.headers['x-frame-options'] || '').toLowerCase();
    // deny all requests
    if(xFrameOp==='deny') return false;
    // deny if different origin
    if(xFrameOp==='sameorigin' && json.origin !== location.origin) return false;
    return true;
  })
}

checkUrlFrameOptions("https://google.com").then((res)=>console.log("google.com can be loaded in iframe: ", res))
checkUrlFrameOptions("https://example.com").then((res)=>console.log("example.com can be loaded in iframe: ", res))

The cloudflare worker endpoint ( https://header-inspector.repalash.workers.dev ) is just for testing, don’t use this in production. The code is available at: https://gist.github.com/repalash/b1e778dbe3ac2e7149831c530a6535f9
and can be deployed directly as a cloudflare worker

OLD Answer

Here’s a simple solution, tested on Chrome and Safari.

    const iframe = document.createElement('iframe')
    iframe.onload = function() {
        try {
            iframe.contentWindow.name
        } catch (e) {
            if (e.message.includes('cross-origin')) console.warn(e.message);
            else console.error(e.message);
        }
    }

    iframe.src = "https://google.com";

jsFiddle demo: https://jsfiddle.net/k5e1mg3t/5/

answered Jun 7, 2021 at 16:40

Palash Bansal's user avatar

2

I faced similar problem. I solved it without using onload handler.I was working on AngularJs project so i used $interval and $ timeout. U can also use setTimeout and setInterval.Here’s the code:

 var stopPolling;
 var doIframePolling;
 $scope.showIframe = true;
 doIframePolling = $interval(function () {
    if(document.getElementById('UrlIframe') && document.getElementById('UrlIframe').contentDocument.head && document.getElementById('UrlIframe').contentDocument.head.innerHTML != ''){
        $interval.cancel(doIframePolling);
        doIframePolling = undefined;
        $timeout.cancel(stopPolling);
        stopPolling = undefined;
        $scope.showIframe = true;
    }
},400);

stopPolling = $timeout(function () {
        $interval.cancel(doIframePolling);
        doIframePolling = undefined;
        $timeout.cancel(stopPolling);
        stopPolling = undefined;
        $scope.showIframe = false;     
},5000);

 $scope.$on("$destroy",function() {
        $timeout.cancel(stopPolling);
        $interval.cancel(doIframePolling);
 });

Every 0.4 Seconds keep checking the head of iFrame Document. I somthing is present.Loading was not stopped by CORS as CORS error shows blank page.
If nothing is present after 5 seconds there was some error (Cors policy) etc..
Show suitable message.Thanks. I hope it solves your problem.

answered Jan 15, 2016 at 11:48

viresh's user avatar

1

As explained in the accepted answer, https://stackoverflow.com/a/18665488/4038790, you need to check via a server.

Because there’s no reliable way to check this in the browser, I suggest you build yourself a quick server endpoint that you can use to check if any url is loadable via iframe. Once your server is up and running, just send a AJAX request to it to check any url by providing the url in the query string as url (or whatever your server desires). Here’s the server code in NodeJs:

const express = require('express')
const app = express()

app.get('/checkCanLoadIframeUrl', (req, res) => {
  const request = require('request')
  const Q = require('q')

  return Q.Promise((resolve) => {
    const url = decodeURIComponent(req.query.url)

    const deafultTimeout = setTimeout(() => {
      // Default to false if no response after 10 seconds
      resolve(false)
    }, 10000)

    request({
        url,
        jar: true /** Maintain cookies through redirects */
      })
      .on('response', (remoteRes) => {
        const opts = (remoteRes.headers['x-frame-options'] || '').toLowerCase()
        resolve(!opts || (opts !== 'deny' && opts !== 'sameorigin'))
        clearTimeout(deafultTimeout)
      })
      .on('error', function() {
        resolve(false)
        clearTimeout(deafultTimeout)
      })
  }).then((result) => {
    return res.status(200).json(!!result)
  })
})

app.listen(process.env.PORT || 3100)

answered Apr 18, 2020 at 23:47

lwdthe1's user avatar

lwdthe1lwdthe1

7771 gold badge12 silver badges12 bronze badges

I have an <iframe> that other sites can include so their users can POST a form back to my site. I’d like to handle gracefully the cases where my site is down or my server can’t serve the <iframe> contents (that is, a response timeout or a 4xx or 5xx error). I tried adding an onError to the <iframe> object, but that didn’t seem to do anything:

showIFrame = function() {
  var iframe = document.createElement('iframe');
  iframe.id = 'myIFrame';
  iframe.src = 'http://myserver.com/someURLThatFailsToLoad';
  iframe.onError = iframe.onerror = myHandler;
  document.body.appendChild(iframe);
};

myHandler = function(error) {
  document.getElementById('myIFrame').style.display = 'none';
  console.error('Error loading iframe contents: ' + error);
  return true;
};

If my server returns a 404 I just get the contents of the not-found page in my <iframe>. In fact, that error handler isn’t ever triggered. Is there a way to make this work?

(I’m currently testing in Chrome, but I’d like it to also work for FF and IE >= 7.)

asked Sep 13, 2010 at 23:11

James A. Rosen's user avatar

James A. RosenJames A. Rosen

63.5k61 gold badges178 silver badges261 bronze badges

To detect whether your server is down or not, you can include an empty script file from your own domain. When the server is down, the onerror event handler will fire:

var el = document.createElement('script');
el.onerror = errorFunction;
el.src = "somebogusscript.js?" + new Date().getTime();
document.body.appendChild(el);

Note: don’t forget to add a random string to the src attribute to avoid the client using a cached version (which could stop a look at the server at all).

answered Sep 13, 2010 at 23:17

Marcel Korpel's user avatar

Marcel KorpelMarcel Korpel

21.5k6 gold badges60 silver badges80 bronze badges

5

One technique is to set a JavaScript timeout when you make the request. If your timeout fires before the iframe onload event, the content didn’t load. You could then set iframe.src to about:blank, delete, or reuse the iframe.

answered Mar 29, 2012 at 8:51

Sam Watkins's user avatar

Sam WatkinsSam Watkins

7,6413 gold badges38 silver badges38 bronze badges



я загружаю некоторый HTML в iframe, но когда файл, на который ссылается, использует http, а не https, я получаю следующую ошибку:

[заблокировано] страница в {current_pagename} запускала небезопасное содержимое из {referenced_filename}

есть ли способ отключить это или любой способ обойти это?

iframe не имеет src атрибут и содержимое задаются с помощью:

frame.open();
frame.write(html);
frame.close();


1163  


8  

8 ответов:

исходя из общности этого вопроса, я думаю, что вам нужно будет настроить свой собственный прокси HTTPS на каком-то сервере в интернете. Выполните следующие действия:

  • подготовьте прокси-сервер-установите IIS, Apache
  • получить действительный сертификат SSL, чтобы избежать ошибок безопасности (бесплатно startssl.com например)
  • напишите обертку, которая будет загружать небезопасный контент (как показано ниже)
  • С вашего сайта/приложения https://yourproxy.com/?page=http://insecurepage.com

Если вы просто загружаете контент удаленного сайта через file_get_contents или similiar, у вас все еще могут быть небезопасные ссылки на контент. Вы должны будете найти их с регулярным выражением, а также заменить. Изображения трудно решить, но я нашел обходной путь здесь:http://foundationphp.com/tutorials/image_proxy.php

Примечание: хотя это решение, возможно, работало в некоторых браузерах, когда оно было написано в 2014 году, оно больше не работает. Навигация или перенаправление на HTTP-URL в iframe встроенный в страницу HTTPS не допускается современными браузерами, даже если фрейм начинался с URL HTTPS.

лучшее решение, которое я создал, — это просто использовать google в качестве прокси ssl…

https://www.google.com/search?q=%http://yourhttpsite.com&btnI=Im+Feeling+Lucky

протестировано и работает в firefox.

другой Методы:

  • использовать сторонних производителей, таких как размещения.лы (но это действительно только хорошо для хорошо известны Апис протоколу HTTP).

  • создайте свой собственный скрипт перенаправления на странице https, которую вы контролируете (простое перенаправление javascript на относительной связанной странице должно сделать трюк. Что-то вроде: (Вы можете использовать любой язык/метод)

    https://example.com который имеет iframe ссылки…

    https://example.com/utilities/redirect.html который имеет простой скрипт перенаправления js как…

    document.location.href ="http://thenonsslsite.com";

  • кроме того, вы можете добавить RSS-канал или написать какой-либо читатель/парсер, чтобы прочитать сайт http и отобразить его на своем сайте https.

  • вы можете/должны также рекомендовать владельцу сайта http, чтобы они создали соединение ssl. Хотя бы по той причине, что это увеличивает seo.

если вы не можете заставить владельца сайта http создать сертификат ssl, то наиболее безопасным и постоянным решением было бы создание RSS-канала, захватывающего контент, который вам нужен (предположительно, вы на самом деле ничего не «делаете» на сайте http-то есть не входите в какую-либо систему).

реальная проблема заключается в том, что наличие элементов http внутри сайта https представляет собой проблему безопасности. Нет никаких полностью кошерных способов обойти этот риск безопасности, поэтому вышеизложенное — это просто текущие обходные пути.

обратите внимание, что вы можете отключить эту меру безопасности в большинство браузеров (сами, а не для других). Также обратите внимание, что эти «хаки» могут устареть с течением времени.

Я знаю, что это старый пост, но другим решением было бы использовать cURL, например:

редирект.php:

<?php
if (isset($_GET['url'])) {
    $url = $_GET['url'];
    $ch = curl_init();
    $timeout = 5;
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
    $data = curl_exec($ch);
    curl_close($ch);
    echo $data;
}

затем в вашем теге iframe, что-то вроде:

<iframe src="/redirect.php?url=http://www.example.com/"></iframe>

это всего лишь минимальный пример, чтобы проиллюстрировать идею — он не дезинфицирует URL-адрес и не мешает кому-то другому использовать перенаправление.PHP для своих целей. Рассмотрим эти вещи в контексте вашего собственного сайта.

плюс, хотя, это больше гибкий. Например, вы можете добавить некоторую проверку данных curl’D$, чтобы убедиться, что это действительно то, что вы хотите, прежде чем отображать его, например, проверить, чтобы убедиться, что это не 404, и иметь альтернативный контент, если он готов.

плюс — я немного устал полагаться на перенаправление Javascript для чего-либо важного.

Ура!

вы всегда будете получать предупреждения о заблокированном контенте в большинстве браузеров при попытке отображения небезопасного контента на странице https. Это сложно, если вы хотите встроить материал с других сайтов, которые не стоят за ssl. Вы можете отключить предупреждения или удалить блокировку в собственном браузере, но и для других посетителей это проблема.

один из способов сделать это-загрузить контент-сервер и сохранить изображения и другие вещи на свой сервер и отобразить их с протокол https.

вы также можете попробовать использовать такую услугу, как embed.ly и получить содержание через них. У них есть поддержка для получения контента за https.

использование Google в качестве прокси SSL в настоящее время не работает,

почему?

если вы открыли любую страницу из google, вы найдете там

вы можете попробовать очистить все, что вам нужно, с помощью PHP или другого языка на стороне сервера, а затем поместить iframe в очищенный контент. Вот пример с PHP:

scrapedcontent.php:

<?php
$homepage = file_get_contents('http://www.example.com/');
echo $homepage;
?>

.html:

<iframe src="scrapedcontent.php"></iframe>

Если речь идет о нескольких и редко меняющихся URL-адресах для внедрения в iframe, вы можете настроить прокси SSL для этого на своем собственном сервере и настроить его так, чтобы один https URL на вашем сервере сопоставляется с одним http URL на проксируемом сервере.

например, я бы заглянул в сайту ngrok и mitmproxy для этого, так как они малы и просты в настройке (хотя обычно предназначены для немного разных целей).

Я загружаю некоторый HTML в iframe, но когда файл, на который ссылается, использует http, а не https, я получаю следующую ошибку:

[заблокировано] На странице {current_pagename} запущен небезопасный контент из {referenced_filename}

Есть ли способ отключить это или каким-либо образом обойти его?

В iframe нет атрибута src, и содержимое устанавливается с помощью:

frame.open();
frame.write(html);
frame.close();

4b9b3361

Ответ 1

Основываясь на общности этого вопроса, я думаю, вам нужно настроить собственный прокси HTTPS на каком-то сервере в Интернете. Выполните следующие действия:

  • Подготовьте свой прокси-сервер — установите IIS, Apache
  • Получить действующий SSL-сертификат, чтобы избежать ошибок безопасности (например, без запуска startssl.com)
  • Напишите обертку, которая загрузит небезопасный контент (как показано ниже)
  • С вашего сайта/приложения получите https://yourproxy.com/?page=http://insecurepage.com

Если вы просто загружаете удаленный контент сайта через file_get_contents или похожий, у вас все еще могут быть небезопасные ссылки на контент. Вам придется найти их с регулярным выражением, а также заменить. Изображения трудно решить, но Ï нашел обходное решение здесь: http://foundationphp.com/tutorials/image_proxy.php

Ответ 2

  Примечание: Хотя это решение могло работать в некоторых браузерах, когда оно было написано в 2014 году, оно больше не работает. Навигация или перенаправление на URL-адрес HTTP в iframe, встроенном в страницу HTTPS, не разрешены современными браузерами, даже если кадр начинался с URL-адреса HTTPS.

Лучшее решение, которое я создал, — просто использовать Google в качестве ssl-прокси…

https://www.google.com/search?q=%http://yourhttpsite.com&btnI=Im+Feeling+Lucky

Проверено и работает в Firefox.

Другие методы:

  • Используйте стороннее устройство, такое как embed.ly (но это хорошо только для хорошо известных http API).

  • Создайте свой собственный скрипт перенаправления на странице https, которой вы управляете (простое перенаправление javascript на относительной связанной странице должно помочь. Что-то вроде: (вы можете использовать любой язык/метод)

    https://example.com У этого есть iframe, связывающий с…

    https://example.com/utilities/redirect.html У которого есть простой скрипт перенаправления js, например…

    document.location.href ="http://thenonsslsite.com";

  • Кроме того, вы можете добавить RSS-канал или написать программу чтения/анализа для чтения http-сайта и отображения его на своем https-сайте.

  • Вы можете/должны также порекомендовать владельцу http-сайта создать ssl-соединение. Если по какой-либо другой причине, кроме , это увеличивает SEO.

Если вы не можете заставить владельца сайта http создать сертификат ssl, наиболее безопасным и постоянным решением будет создание RSS-канала, собирающего необходимый вам контент (возможно, вы на самом деле ничего не делаете на сайте http -that). сказать не входя ни в какую систему).

Реальная проблема заключается в том, что наличие http-элементов на сайте https представляет проблему безопасности. Не существует абсолютно кошерных способов обойти эту угрозу безопасности, поэтому вышесказанное — это просто обходные пути.

Обратите внимание, что вы можете отключить эту меру безопасности в большинстве браузеров (самостоятельно, а не для других). Также обратите внимание, что эти «хаки» могут со временем устареть.

Ответ 3

Я знаю, что это старый пост, но другим решением будет использование cURL, например:

redirect.php:

<?php
if (isset($_GET['url'])) {
    $url = $_GET['url'];
    $ch = curl_init();
    $timeout = 5;
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
    $data = curl_exec($ch);
    curl_close($ch);
    echo $data;
}

то в вашем теге iframe, например:

<iframe src="/redirect.php?url=http://www.example.com/"></iframe>

Это всего лишь пример MINIMAL, чтобы проиллюстрировать эту идею: она не дезинфицирует URL-адрес и не позволяет кому-то другому использовать redirect.php для своих целей. Рассмотрим эти вещи в контексте вашего собственного сайта.

Однако, наоборот, он более гибкий. Например, вы можете добавить некоторую проверку данных curl’d $, чтобы убедиться, что это действительно то, что вы хотите, перед ее отображением — например, проверить, чтобы убедиться, что это не 404, и иметь альтернативный контент самостоятельно, если он есть.

Плюс — я немного устал полагаться на переадресацию Javascript для чего-то важного.

Ура!

Ответ 4

добавить <meta http-equiv="Content-Security-Policy" content="upgrade-insecure-requests"> в голову

reference: http://thehackernews.com/2015/04/disable-mixed-content-warning.html

browser compatibility: http://caniuse.com/#feat=upgradeinsecurerequests

Ответ 5

Вы всегда будете получать предупреждения о заблокированном контенте в большинстве браузеров при попытке отобразить небезопасный контент на странице https. Это сложно, если вы хотите встраивать материал с других сайтов, которые не находятся за пределами ssl. Вы можете отключить предупреждения или удалить блокировку в своем браузере, но для других посетителей это проблема.

Один из способов сделать это — загрузить сервер содержимого и сохранить изображения и другие вещи на свой сервер и отобразить их с https.

Вы также можете попробовать использовать службу, например embed.ly, и получить контент через них. У них есть поддержка для получения контента за https.

Ответ 6

Использование Google в качестве SSL-прокси в настоящее время не работает,

Почему?

Если вы открыли какую-либо страницу из Google, вы обнаружите, что в заголовке есть поле x-frame-options.
Google response header

Заголовок ответа HTTP X-Frame-Options можно использовать, чтобы указать, следует ли разрешить браузеру отображать страницу в <frame>, <iframe> или <object>. Сайты могут использовать это, чтобы избежать атак с помощью клик-джеккинга, обеспечивая что их содержание не встроено в другие сайты.

(Цитата из MDN)

Одно из решений

Ниже приведены мои решения этой проблемы:

Загрузите контент в AWS S3, и он создаст ссылку https для ресурса.
Примечание. Установите разрешение для файла html, чтобы каждый мог его просматривать.

После этого мы можем использовать его как src iframe на веб-сайтах https.
AWS

Ответ 7

Вы можете попробовать соскабливать все, что вам нужно, с PHP или другим языком на стороне сервера, а затем помещать iframe в очищенное содержимое. Вот пример с PHP:

scrapedcontent.php:

<?php
$homepage = file_get_contents('http://www.example.com/');
echo $homepage;
?>

index.html

<iframe src="scrapedcontent.php"></iframe>

Ответ 8

Используйте свой собственный обратный прокси-сервер HTTPS-HTTP.

Если в вашем случае используется несколько редко меняющихся URL-адресов для встраивания в iframe, вы можете просто настроить обратный прокси-сервер для этого на своем собственном сервере и настроить его так, чтобы один URL-адрес https на вашем сервере соответствовал одному http URL на прокси-сервере. Поскольку обратный прокси-сервер полностью находится на стороне сервера, браузер не может обнаружить, что он «только» общается с прокси-сервером реального веб-сайта, и, таким образом, не будет жаловаться, поскольку подключение к прокси-серверу правильно использует SSL.

Например, если вы используете Apache2 в качестве веб-сервера, см. эти инструкции, чтобы создать обратный прокси-сервер.

Have you tried using iFrames in another browser?

by Milan Stanojevic

Milan has been enthusiastic about technology ever since his childhood days, and this led him to take interest in all PC-related technologies. He’s a PC enthusiast and he… read more


Updated on August 10, 2022

Fact checked by
Alex Serban

Alex Serban

After moving away from the corporate work-style, Alex has found rewards in a lifestyle of constant analysis, team coordination and pestering his colleagues. Holding an MCSA Windows Server… read more

  • If iFrame is not working in Chrome, the easiest solution would be to try a completely different browser.
  • But if you’re keen on solving this issue, the reason might be that the browser is blocking iFrame.
  • This may also be caused by third-party extensions or even your antivirus.

How to fix iFrame not working in Chrome

Strugling with your current browser? Upgrade to a better one: OperaYou deserve a better browser! 350 million people use Opera daily, a fully-fledged navigation experience that comes with various built-in packages, enhanced resource consumption and great design. Here’s what Opera can do:

  • Easy migration: use the Opera assistant to transfer exiting data, such as bookmarks, passwords, etc.
  • Optimize resource usage: your RAM memory is used more efficiently than in other browsers
  • Enhanced privacy: free and unlimited VPN integrated
  • No ads: built-in Ad Blocker speeds up loading of pages and protects against data-mining
  • Gaming friendly: Opera GX is the first and best browser for gaming
  • Download Opera

A great number of users have reported encountering issues when trying to use iFrames in their HTML document. The message states that this file can only be viewed in an iFrame.

Furthermore, a good number of varied browsers have shown an error message saying Browser does not support iFrames.

The issue occurs seems to appear when trying to add iFrame on an SSL- encrypted website (HTTPS://).

Inline frames, called iFrames for short, are the only type of frame permitted in HTML5 so it’s pretty important.

To better understand iFrame, it’s like a browser window that resides inside a web page. And its mostly seen on websites that display external content, for instance, a YouTube player or a Google map.

Why iFrame is not working in Chrome?

It’s really a simple issue here because Chrome is usually blocking iFrame and that’s the main reason you’re getting the error.

However, iFrame may also be blocked from your Internet Options, by your antivirus or by an add-on you just installed in Chrome.

The issue is mainly associated with Google Chrome, but it can also affect Mozilla users.

The security features of these browsers were set up to block all unencrypted content for encrypted websites.

So, in this article, we will show you exactly how to enable iFrame in Chrome. Furthermore, we shall explore some of the best-proven methods to solve this issue and similar problems, such as:

  • iFrames are getting blocked by the Chrome Browser – If that’s your problem too, disable, then enable iFrames back from Internet Options
  • iFrame not working in Chrome – Make sure you get rid of it right away by stopping your antivirus service or using a completely different browser
  • Enable iFrame in Chrome – Chrome randomly rejects iFrame, so make sure to enable it or use an add-on
  • This file can only be viewed in an iFrame – This is the common message of the iFrame error
  • The iFrame has not configured – see suggestions in console – iFrame is most likely disabled
  • Your browser does not support frames, so you will not be able to view this page – You are using a browser that doesn’t support iFrame
  • iFrame not loading in Chrome unless the window is resized – Resize the window to load iFrame

Quick tip:

Opera Browser offers great security, yet it is way less intrusive than its counterparts and has a wider compatibility range. Therefore, it easily supports iFrames.

In addition, the software has anti-tracking protection and a built-in VPN, so you can rest assured that your browsing activity is completely private.

Opera

If your current browser does not support iFrames, Opera might surprise you. Give it a try!

Is iFrame supported by all browsers?

Yes, iFrame is supported by all modern desktop and mobile browsers but not all of them are able to respond to the new attributes from HTML5.

So, the best browsers that work with iFrame are the ones that updated their HTML5 compatibility and its new elements.

What can I do if iFrame doesn’t work in Chrome?

1. Disable/enable iFrames from Internet Options

  1. Click on the Windows Search tab, type in Internet Options, and select the first option.
  2. Select the Security tab.
  3. Click on the Custom level button.internet properties security options and custom level button - browser doesn't support iframes
  4. Scroll down to Launching programs and files in an IFRAME option.
  5. Now, select Disable if you want to remove it completely, or Prompt to choose for each website you visit.Security settings internet zone - browser doesn't support iframes
  6. Repeat steps 4 and 5 of this method for each of the desired security zones.
  7. Click Ok to apply and exit the Internet Options menu.
  8. Check to see if this method solved your issue.

2. Stop your antivirus service

  1. Depending on the antivirus software you’re using, these steps will vary. (we are using BitDefender for this example).
  2. Open up BitDefender.
  3. Select the Protection tab.Disable antivirus protection BitDefender Total Security - browser does not support iframes
  4. Select Settings under the Antivirus section and toggle the blue button to deactivate protection.
  5. Check to see if the issue still persists.

We have shown you how to disable the feature in BitDefender but the method is very similar in all other antiviruses.

3. Disable all add-ons from your browser

  1. In Chrome, select the three dots at the top-right side of your screen, select More tools, then choose Extensions.
  2. Inside the Extensions window, de-activate all add-ons.Disable extensions in Chrome - Browser does not support iframes
  3. Try to see if this method solved your issue.

4. Download add-ons to allow iFrames

4.1 Add extension to Chrome

  1. Open Google Chrome.
  2. Visit this Chrome Store address.
  3. Click on the Add to Chrome button, then select Add extension.Click on Add extension - Browser doesn't support iframes
  4. Restart Google Chrome and check to see if the issue is solved.

If iFrame is not working in Chrome, this extension will make things right and the element should start running without any issues.

This solution should also fix the problem if iFrame PDF iFrame autoplay iFrame.onload and iFrame print are not working in Chrome.

4.2 Add extension to Firefox

  1. Open Mozilla Firefox.
  2. Download the extension from Firefox store.
  3. Select Add to Firefox.Firefox addons add button - Browser doesn't support iframes
  4. Select Add from the pop-up window.Add Open Frame to firefox - Browser doesn't support iframes
  5. Restart Firefox and check to see if the issues are resolved.

If iFrame is not working in Firefox, the extension we recommended above should fix the issue and now it should be all right.

Some of our readers told us that iFrame is not working in Edge either but unfortunately, there is no plug-in to enable it.

Thus, if the issue persists, you should definitely try using another browser as we suggested in Step 1 of this guide.

Read more about this topic

  • How to enable autoplay for embedded YouTube videos
  • Couldn’t load the plugin on Chrome: 2 quick ways to fix this error
  • Webpage Might be Temporarily Down or it may Have Moved

iFrame is not working in Chrome but works in Firefox

Google Chrome has a different set of rules when it comes to iFrame and it often blocks the content although it works fine on other browsers.

You should also try clicking the shield in the URL title bar because that would also help you see the content.

If you press Ctrl + Shift + J in Chrome, you will see information about the blocked content and the reason for this.

In this article, we explored some of the best-proven methods to solve the issue caused by your browser not allowing you to use/show iFrames.

Make sure to follow these steps closely to sort out the iFrame not working in Chrome issue.

You can also read our guide on fixing This content cannot be displayed in a frame error which addresses the issue on Internet Explorer.

Feel free to share your experience with us by using the comments section below.

newsletter icon

Newsletter

Понравилась статья? Поделить с друзьями:
  • Iframe error event
  • Ifnet error link updown
  • Ifile не прошел регистрацию как исправить
  • Ifh 0018 initialization error inpa ошибка
  • Ifh 0009 ошибка inpa