How to set the <img> tag with basic authentication - html

I would like to display the image from a network camera on my web page, but the image is behind a HTTP basic authentication server.
In Firefox and Chrome I can do this:
<img width="320" height="200" src="http://username:password#server/Path" />
But in Internet Explorer 8, I get an empty image box. If I use JQuery to set the src attribute, IE8 displays a blank src. It looks like IE8 is checking the string and rejecting it.
Is there a way to put the basic authentication credentials in the img tag?

Bottom line: Not all browsers allow this. It may work in some but not others.
But as someone else has said already, it's not very safe -- you're effectively giving the login and password details to anyone who browses the page. Not good.
A better option would be proxy it through the same server that you're providing the html code from, then the href in the <img> tag could just be a local URL, and no-one need know where the image is actually coming from.

You can load your img with AJAX, using XMLHttpRequest. As you might know, XMLHttpRequest has a setRequestHeaders method, so you will be able to manipulate headers for your request, hence, you will be able to do basic HTTP authentication.

Best way is to create a login page, then setup port forwarding on your router to display the camera. Does the camera come with web software?

See http://support.microsoft.com/kb/834489 and http://msdn.microsoft.com/en-us/library/ie/ee330735(v=vs.85).aspx#login_creds_urls
Long story short, usernames/passwords are not formally supported under the HTTP/HTTPS protocol schemes and due to their use in phishing attacks, they were disabled in IE6 on XPSP2. Support can be manually re-enabled by the user using a registry override (FEATURE_HTTP_USERNAME_PASSWORD_DISABLE) but this is not recommended.

Try http proxy.
On server side, enable tinyProxy, create ReversePath to
basic authentication server in configuration like:
AddHeader "Authorization" "Basic dXNlcjpwYXNz"
ReversePath "/foo/" "http://somewhere:3480/foo/"
dXNlcjpwYXNz is base64 encoded string from user:pass
Enable reverse proxy in Apache or NGINX to tinyProxy path http://localhot:8888/foo/
Img Source accessable from local server instead of old way deprecated, without http auth pop-up or CORS error.
http://user:pass#somewhere:3480/foo/DEST.jpg

ajax add http header works!
pictureUrl = "https://somewhere/file.jpg";
var oReq = new XMLHttpRequest();
oReq.open("GET", pictureUrl, true);
oReq.setRequestHeader("Authorization", "Basic " + btoa("UserName"+":"+"Password"));
// use multiple setRequestHeader calls to set multiple values
oReq.responseType = "arraybuffer";
oReq.onload = function (oEvent) {
var arrayBuffer = oReq.response; // Note: not oReq.responseText
if (arrayBuffer) {
var u8 = new Uint8Array(arrayBuffer);
var b64encoded = btoa(String.fromCharCode.apply(null, u8));
var mimetype="image/jpeg"; // or whatever your image mime type is
document.getElementById("iOdata").src="data:"+mimetype+";base64,"+b64encoded;
}
};
oReq.send(null);

Related

HTML does not display text file hosted by a specific site [duplicate]

I'm writing a tiny webpage whose purpose is to frame a few other pages, simply to consolidate them into a single browser window for ease of viewing. A few of the pages I'm trying to frame forbid being framed and throw a "Refused to display document because display forbidden by X-Frame-Options." error in Chrome. I understand that this is a security limitation (for good reason), and don't have access to change it.
Is there any alternative framing or non-framing method to display pages within a single window that won't get tripped up by the X-Frame-Options header?
I had a similar issue, where I was trying to display content from our own site in an iframe (as a lightbox-style dialog with Colorbox), and where we had an server-wide "X-Frame-Options SAMEORIGIN" header on the source server preventing it from loading on our test server.
This doesn't seem to be documented anywhere, but if you can edit the pages you're trying to iframe (eg., they're your own pages), simply sending another X-Frame-Options header with any string at all disables the SAMEORIGIN or DENY commands.
eg. for PHP, putting
<?php
header('X-Frame-Options: GOFORIT');
?>
at the top of your page will make browsers combine the two, which results in a header of
X-Frame-Options SAMEORIGIN, GOFORIT
...and allows you to load the page in an iframe. This seems to work when the initial SAMEORIGIN command was set at a server level, and you'd like to override it on a page-by-page case.
All the best!
If you are getting this error for a YouTube video, rather than using the full url use the embed url from the share options. It will look like http://www.youtube.com/embed/eCfDxZxTBW4
You may also replace watch?v= with embed/ so http://www.youtube.com/watch?v=eCfDxZxTBW4 becomes http://www.youtube.com/embed/eCfDxZxTBW4
If you are getting this error while trying to embed a Google Map in an iframe, you need to add &output=embed to the source link.
UPDATE 2019: You can bypass X-Frame-Options in an <iframe> using just client-side JavaScript and my X-Frame-Bypass Web Component. Here is a demo: Hacker News in an X-Frame-Bypass. (Tested in Chrome & Firefox.)
There is a plugin for Chrome, that drops that header entry (for personal use only):
https://chrome.google.com/webstore/detail/ignore-x-frame-headers/gleekbfjekiniecknbkamfmkohkpodhe/reviews
Adding a
target='_top'
to my link in the facebook tab fixed the issue for me...
If you're getting this error trying to embed Vimeo content, change the src of the iframe, from: https://vimeo.com/63534746 to: http://player.vimeo.com/video/63534746
I had same issue when I tried embed moodle 2 in iframe, solution is Site administration ► Security ► HTTP security and check Allow frame embedding
Solution for loading an external website into an iFrame even tough the x-frame option is set to deny on the external website.
If you want to load a other website into an iFrame and you get the Display forbidden by X-Frame-Options” error then you can actually overcome this by creating a server side proxy script.
The src attribute of the iFrame could have an url looking like this: /proxy.php?url=https://www.example.com/page&key=somekey
Then proxy.php would look something like:
if (isValidRequest()) {
echo file_get_contents($_GET['url']);
}
function isValidRequest() {
return $_SERVER['REQUEST_METHOD'] === 'GET' && isset($_GET['key']) &&
$_GET['key'] === 'somekey';
}
This by passes the block, because it is just a GET request that might as wel have been a ordinary browser page visit.
Be aware: You might want to improve the security in this script. Because hackers could start loading in webpages via your proxy script.
This is the solution guys!!
FB.Event.subscribe('edge.create', function(response) {
window.top.location.href = 'url';
});
The only thing that worked for facebook apps!
I tried nearly all suggestions. However, the only thing that really solved the issue was:
Create an .htaccess in the same folder where your PHP file lies.
Add this line to the htaccess:
Header always unset X-Frame-Options
Embedding the PHP by an iframe from another domain should work afterwards.
Additionally you could add in the beginning of your PHP file:
header('X-Frame-Options: ALLOW');
Which was, however, not necessary in my case.
It appears that X-Frame-Options Allow-From https://... is depreciated and was replaced (and gets ignored) if you use Content-Security-Policy header instead.
Here is the full reference: https://content-security-policy.com/
I had the same problem with mediawiki, this was because the server denied embedding the page into an iframe for security reasons.
I solved it writing
$wgEditPageFrameOptions = "SAMEORIGIN";
into the mediawiki php config file.
Hope it helps.
Not mentioned but can help in some instances:
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState !== 4) return;
if (xhr.status === 200) {
var doc = iframe.contentWindow.document;
doc.open();
doc.write(xhr.responseText);
doc.close();
}
}
xhr.open('GET', url, true);
xhr.send(null);
FWIW:
We had a situation where we needed to kill our iFrame when this "breaker" code showed up. So, I used the PHP function get_headers($url); to check out the remote URL before showing it in an iFrame. For better performance, I cached the results to a file so I was not making a HTTP connection each time.
I was using Tomcat 8.0.30, none of the suggestions worked for me. As we are looking to update the X-Frame-Options and set it to ALLOW, here is how I configured to allow embed iframes:
Navigate to Tomcat conf directory, edit the web.xml file
Add the below filter:
<filter>
<filter-name>httpHeaderSecurity</filter-name>
<filter-class>org.apache.catalina.filters.HttpHeaderSecurityFilter</filter-class>
<init-param>
<param-name>hstsEnabled</param-name>
<param-value>true</param-value>
</init-param>
<init-param>
<param-name>antiClickJackingEnabled</param-name>
<param-value>true</param-value>
</init-param>
<init-param>
<param-name>antiClickJackingOption</param-name>
<param-value>ALLOW-FROM</param-value>
</init-param>
<async-supported>true</async-supported>
</filter>
<filter-mapping>
<filter-name>httpHeaderSecurity</filter-name>
<url-pattern>/*</url-pattern>
<dispatcher>REQUEST</dispatcher>
</filter-mapping>
Restart Tomcat service
Access the resources using an iFrame.
The only question that has a bunch of answers. WElcome to the guide i wish i had when i was scrambling for this to make it work at 10:30 at night on the deadline day... FB does some weird things with canvas apps, and well, you've been warned. If youa re still here and you have a Rails app that will appear behind a Facebook Canvas, then you will need:
Gemfile:
gem "rack-facebook-signed-request", :git => 'git://github.com/cmer/rack-facebook-signed-request.git'
config/facebook.yml
facebook:
key: "123123123123"
secret: "123123123123123123secret12312"
config/application.rb
config.middleware.use Rack::Facebook::SignedRequest, app_id: "123123123123", secret: "123123123123123123secret12312", inject_facebook: false
config/initializers/omniauth.rb
OmniAuth.config.logger = Rails.logger
SERVICES = YAML.load(File.open("#{::Rails.root}/config/oauth.yml").read)
Rails.application.config.middleware.use OmniAuth::Builder do
provider :facebook, SERVICES['facebook']['key'], SERVICES['facebook']['secret'], iframe: true
end
application_controller.rb
before_filter :add_xframe
def add_xframe
headers['X-Frame-Options'] = 'GOFORIT'
end
You need a controller to call from Facebook's canvas settings, i used /canvas/ and made the route go the main SiteController for this app:
class SiteController < ApplicationController
def index
#user = User.new
end
def canvas
redirect_to '/auth/failure' if request.params['error'] == 'access_denied'
url = params['code'] ? "/auth/facebook?signed_request=#{params['signed_request']}&state=canvas" : "/login"
redirect_to url
end
def login
end
end
login.html.erb
&lt% content_for :javascript do %>
var oauth_url = 'https://www.facebook.com/dialog/oauth/';
oauth_url += '?client_id=471466299609256';
oauth_url += '&redirect_uri=' + encodeURIComponent('https://apps.facebook.com/wellbeingtracker/');
oauth_url += '&scope=email,status_update,publish_stream';
console.log(oauth_url);
top.location.href = oauth_url;
&lt% end %>
Sources
The config i think came from omniauth's example.
The gem file (which is key!!!) came from: slideshare things i learned...
This stack question had the whole Xframe angle, so you'll get a blank space, if
you don't put this header in the app controller.
And my man #rafmagana wrote this heroku guide, which now you can adopt for rails with this answer and the shoulders of giants in which you walk with.
The only real answer, if you don't control the headers on your source you want in your iframe, is to proxy it. Have a server act as a client, receive the source, strip the problematic headers, add CORS if needed, and then ping your own server.
There is one other answer explaining how to write such a proxy. It isn't difficult, but I was sure someone had to have done this before. It was just difficult to find it, for some reason.
I finally did find some sources:
https://github.com/Rob--W/cors-anywhere/#documentation
^ preferred. If you need rare usage, I think you can just use his heroku app. Otherwise, it's code to run it yourself on your own server. Note sure what the limits are.
whateverorigin.org
^ second choice, but quite old. supposedly newer choice in python: https://github.com/Eiledon/alloworigin
then there's the third choice:
http://anyorigin.com/
Which seems to allow a little free usage, but will put you on a public shame list if you don't pay and use some unspecified amount, which you can only be removed from if you pay the fee...
<form target="_parent" ... />
Using Kevin Vella's idea, I tried using the above on the form element made by PayPal's button generator. Worked for me so that Paypal does not open in a new browser window/tab.
Update
Here's an example:
Generating a button as of today (01-19-2021), PayPal automatically includes target="_top" on the form element, but if that doesn't work for your context, try a different target value. I suggest _parent -- at least that worked when I was using this PayPal button.
See Form Target Values for more info.
<form action="https://www.paypal.com/cgi-bin/webscr" method="post" target="_parent">
<input type="hidden" name="cmd" value="_xclick">
<input type="hidden" name="business" value="name#email.com">
<input type="hidden" name="lc" value="US">
<input type="hidden" name="button_subtype" value="services">
<input type="hidden" name="no_note" value="0">
<input type="hidden" name="currency_code" value="USD">
<input type="hidden" name="bn" value="PP-BuyNowBF:btn_buynowCC_LG.gif:NonHostedGuest">
<input type="image" src="https://www.paypalobjects.com/en_US/i/btn/btn_buynowCC_LG.gif" border="0" name="submit" alt="PayPal - The safer, easier way to pay online!">
<img alt="" border="0" src="https://www.paypalobjects.com/en_US/i/scr/pixel.gif" width="1" height="1">
</form>
I'm not sure how relevant it is, but I built a work-around to this. On my site, I wanted to display link in a modal window that contained an iframe which loads the URL.
What I did is, I linked the click event of the link to this javascript function. All this does is make a request to a PHP file that checks the URL headers for X-FRAME-Options before deciding whether to load the URL within the modal window or to redirect.
Here's the function:
function opentheater(link, title){
$.get( "url_origin_helper.php?url="+encodeURIComponent(link), function( data ) {
if(data == "ya"){
$(".modal-title").html("<h3 style='color:480060;'>"+title+" <small>"+link+"</small></h3>");
$("#linkcontent").attr("src", link);
$("#myModal").modal("show");
}
else{
window.location.href = link;
//alert(data);
}
});
}
Here's the PHP file code that checks for it:
<?php
$url = rawurldecode($_REQUEST['url']);
$header = get_headers($url, 1);
if(array_key_exists("X-Frame-Options", $header)){
echo "nein";
}
else{
echo "ya";
}
?>
Hope this helps.
I came across this issue when running a wordpress web site. I tried all sorts of things to fix it and wasn't sure how, ultimately the issue was because I was using DNS forwarding with masking, and the links to external sites were not being addressed properly. i.e. my site was hosted at http://123.456.789/index.html but was masked to run at http://somewebSite.com/index.html. When i entered http://123.456.789/index.html in the browser clicking on those same links resulted in no X-frame-origins issues in the JS console, but running http://somewebSite.com/index.html did. In order to properly mask you must add your host's DNS name servers to your domain service, i.e. godaddy.com should have name servers of example, ns1.digitalocean.com, ns2.digitalocean.com, ns3.digitalocean.com, if you were using digitalocean.com as your hosting service.
It's surprising that no one here has ever mentioned Apache server's settings (*.conf files) or .htaccess file itself as being a cause of this error. Search through your .htaccess or Apache configuration files, making sure that you don't have the following set to DENY:
Header always set X-Frame-Options DENY
Changing it to SAMEORIGIN, makes things work as expected:
Header always set X-Frame-Options SAMEORIGIN
i had this problem, and resolved it editing httd.conf
<IfModule headers_module>
<IfVersion >= 2.4.7 >
Header always setifempty X-Frame-Options GOFORIT
</IfVersion>
<IfVersion < 2.4.7 >
Header always merge X-Frame-Options GOFORIT
</IfVersion>
</IfModule>
i changed SAMEORIGIN to GOFORIT
and restarted server
Site owners use the X-Frame-Options response header so that their website cannot be opened in an Iframe. This helps to secure the users against clickjacking attack
There are a couple of approaches that you can try if you want to disable X-Frame-Options on your own machine.
Configuration at Server-Side
If you own the server or can work with the site owner then you can ask to set up a configuration to not send the Iframe buster response headers based on certain conditions. Conditions could be an additional request header or a parameter in the URL.
For example - The site owner can add an additional code to not send Iframe buster headers when the site is opened with ?in_debug_mode=true query param.
Use Browser extension like Requestly to remove response headers
You can use any browser extension like Requestly which allows you to modify the request & response headers. Here's a Requestly blog that explains how to embed sites in Iframe by bypassing Iframe buster headers.
Configure a Pass-through Proxy and remove headers from it
If you need to bypass Iframe buster headers for multiple folks, then you can also configure a pass-through proxy that just removes the frame buster response headers and return back the response. This is however a lot complicated to write, set up. There are some other challenges like authentication etc with the sites opened in Iframe through a proxy but this approach can work for simple sites pretty well.
PS - I have built both solutions and have first-hand experience with both.
Edit .htaccess if you want to remove X-Frame-Options from an entire directory.
And add the line: Header always unset X-Frame-Options
[contents from: Overcoming "Display forbidden by X-Frame-Options"
Use this line given below instead of header() function.
echo "<script>window.top.location = 'https://apps.facebook.com/yourappnamespace/';</script>";
Try this thing, i dont think anyone suggested this in the Topic, this will resolve like 70% of your issue, for some other pages, you have to scrap, i have the full solution but not for public,
ADD below to your iframe
sandbox="allow-same-origin allow-scripts allow-popups allow-forms"

Display image that returns HTTP 503 in Firefox

I have a status badge image that returns the HTTP code 503 when the respective service is offline (but the webserver is still there serving calls). Now opening the image URL directly will display the image properly, regardless of the underlying 503 error code. But using it inside an <img> tag shows the broken image icon. How can I prevent that while still allowing the image itself to return a 503? (External services depend on that)
Here are some screenshots to illustrate what's going on:
The badge on the page:
The status message in the developer console:
The badge itself:
Note: This happens on Firefox. Not Chrome
Edit: Here are a few requested pieces information:
Firefox 78.0.2 (64-Bit)
It's served from the same domain. But the domain is essentially just proxying serveral underlying webservices. And this badge is originating from a different service but all on the same domain.
It's a SVG image if that makes any difference.
Since XMLHttpRequest can retrieve the output of any request, no matter the response code, it is possible to request for the image with XMLHttpRequest, and then convert the blob response type to a base64 format image, which can be loaded in the browser.
The CORS proxy I used in the sample code may not be necessary in the majority of cases, but could be useful in the case where the image you are trying to display has weird response headers that prevent access to the image from another domain.
Here is the sample code. It should work no matter the response code, CORS, etc.
var xhr = new XMLHttpRequest();
xhr.onload = function () {
var reader = new FileReader();
reader.onloadend = function () {
// here, reader.result contains the base64-formatted string you can use to set the src attribute with
document.getElementsByTagName('img')[0].src = reader.result; // sets the first <img> tag to display the image, change to the element you want to use
};
reader.readAsDataURL(xhr.response);
};
xhr.open('GET', "https://cors-anywhere.herokuapp.com/i.stack.imgur.com/8wB1j.png"); // don't include the HTTP/HTTPS protocol in the url
xhr.responseType = 'blob';
xhr.setRequestHeader('X-Requested-With', 'xhr');
xhr.send();
<img src="about:blank">
Everything works, as when you go into Inspect Element, you see that the src attribute of the <img> tag points to a base64 URL that can load in any browser.
You might want to compress or resize your images before uploading it to server , as they might be large enough to keep the server busy and show the error as most of the time, a 503 error occurs because the server is too busy.
More over the image is SVG so it might render dimesions before completing, hence I'd suggest
Try replacing the SVG with PNG or JPG
Also try for site like https://tinypng.com/ to compress the image size
This might work for you

Bypass blocking of subresource requests whose URLs contain embedded credentials

I have been automatically authenticating users visiting our internal wiki via a link with a token in the URL like this:
href="https://user:pass#host/"
In Chrome 59, this is being prevented.
[Deprecation] Subresource requests whose URLs contain embedded credentials (e.g. https://user:pass#host/) are blocked.
I read and I bypassed it in an ajax request like this:
how to replace embedded credentials in subresource requests
========================================================================
My Question is:
Does anyone know how to do it directly in the link, or can you provide some kind of workaround? Is this even possible?
Passing the command line option '--disable-blink-features=BlockCredentialedSubresources' restores the expected behavior. If you're using Selneium, you can pass it as an args option in the Browser Capabilities to restore the expected behavior.
PHP:
'chromeOptions' => array('args' => ['--disable-blink-features=BlockCredentialedSubresources']);
Python:
capabilities['chromeOptions'] = {'args': ['--headless']}
According to the Chromium ticket (https://bugs.chromium.org/p/chromium/issues/detail?id=731618) this behavior may not be restored in future versions despite it being in 'Deprecation'. In this case, it might be best to look at ssh conduits for testing or whitelist the IP if possible to prevent the HTTP Auth interaction.
Anthony
If your page includes css, javascript or other stuff with relative ("folder/file") or base-relative ("/folder/file") locations, then the problem is that these included files would be fetched from a URL relative to the base URL of the page, which includes a user:pass component.
It is that user:pass componenent (which you possibly never meant to imply anyway...) which makes the URL of the subresources illegal, following this change to Chrome.
If that is your problem, you can fix it by adding a <base href="https://host/"> tag to your page (i.e. the same base address, but without the user:pass component). (If your page is in a subdirectory, you need to include the subdirectory in the base href as well, for fully relative URLs to work.)
To be clear, links like Link still work (as long as the user:pass URL is in a link which opens in a new page, and is not a URL for an iframe, say - that is now banned). But even when the link works, the problem I've described above applies to elements included with relative paths in the newly opened page.
UPDATE:
This has been accepted as a bug in Chrome, directly related to the new changes banning user:pass in subresource URLs. Unfortunately, following through the links in that discussion, it seems that one proposed and quite likely solution is to remove support for user:pass URLs entirely. Any informed comments added to that discussion and arguing in favour of keeping this feature would presumably help.
To handle this, we have to pass chrome options : "--disable-blink-features=BlockCredentialedSubresources");
Complete code is mentioned below :
ChromeOptions options = new ChromeOptions();
options.addArguments("--start-maximized");
options.addArguments("--disable-blink-features=BlockCredentialedSubresources");
Map<String, Object> prefs = new HashMap<String, Object>();
prefs.put("credentials_enable_service", false);
prefs.put("profile.password_manager_enabled", false);
options.setExperimentalOption("prefs", prefs);
DesiredCapabilities capabilities = DesiredCapabilities.chrome();
capabilities.setCapability(ChromeOptions.CAPABILITY, options);
driver = new ChromeDriver(capabilities);

detect iframe load error

I am loading a user-selected page into an iframe using the src property. If the load fails, I would like to report the problem in terms that will make sense to the user. iframe does not, in general, support onerror according to http://www.w3schools.com/jsref/dom_obj_frame.asp.
The page may come from the user's domain, not mine, so I cannot view the content of the iframe.
I can set a timeout and cancel it from my onload handler if the load is successful, but it would need to be a long timeout to avoid false error reports, and meanwhile Safari on my iPhone has displayed an alert that may confuse the user. Even this does not work for the Kindle Fire browser - it delivers a load event to my handler regardless of whether the load was successful.
Is there any event I can use to detect failure? Is there any way to suppress the default Safari behavior? Any way I can tell whether the load attempt has failed? (If I could do that, I could use a shorter timeout and poll until the load attempt is resolved).
I can require the use of up to date browsers, but would like a solution that is portable among as many smartphones and tablets as possible.
I have tested the AJAX Get idea, and it unfortunately does not work. A cross-domain AJAX Get to an arbitrary URI results in an exception, regardless of whether the target exists and can be loaded into the iframe or not.
You could set your iframe and/or ajax request to always call a page you control (ie: loader.php), sending loader.php the user's requested page via get. From loader.php, use curl or even just file_get_contents to fetch the external page. If the request fails to come back to loader.php, you can check the error there, and return whatever you want your iframe to display.
While my example references the use of php, curl is supported in a variety of scripting languages. It is likely more complicated than other solutions you might have, but would give you access to the response headers as well for troubleshooting why a page load failed.
As you've hinted, you'll face same-origin-policy type restrictions when you try to query anything inside the iframe if it's on a separate domain.
You could make an AJAX GET request to the iframe's URL before you pass it into the src of the frame. If you don't get an HTTP 200 response back from the AJAX call, then the site won't be able to load inside the frame either.
This will add overhead to the whole process, and is only useful if you're checking whether the iframe's document is a real URL that works. It won't help if you need to know when the iframe document has fully loaded.
If you need to know when the iframe has loaded, and it's on an external domain, then I believe you have no other option but to ask for some code to be added to those external sites to notify the parent page that they've loaded successfully.
Or, if it makes sense to do so, ask the end user to click a link to flag up that the content isn't loading correctly.
Late to the party, but I've managed to crack it:
At first, I thought to do an AJAX call like everyone else, except that it didn't work for me initially, as I had used jQuery. It works perfectly if you do a XMLHttpRequest:
var url = http://url_to_test.com/
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status != 200) {
console.log("iframe failed to load");
}
};
xhttp.open("GET", url, true);
xhttp.send();
Edit:
So this method works ok, except that it has a lot of false negatives (picks up a lot of stuff that would display in an iframe) due to cross-origin malarky. The way that I got around this was to do a CURL/Web request on a server, and then check the response headers for a) if the website exists, and b) if the headers had set x-frame-options.
This isn't a problem if you run your own webserver, as you can make your own api call for it.
My implementation in node.js:
app.get('/iframetest',function(req,res){ //Call using /iframetest?url=url - needs to be stripped of http:// or https://
var url = req.query.url;
var request = require('https').request({host: url}, function(response){ //This does an https request - require('http') if you want to do a http request
var headers = response.headers;
if (typeof headers["x-frame-options"] != 'undefined') {
res.send(false); //Headers don't allow iframe
} else {
res.send(true); //Headers don't disallow iframe
}
});
request.on('error',function(e){
res.send(false); //website unavailable
});
request.end();
});

Chrome extension, replace HTML in response code before browser displays it

i wonder if there is some way to do something like that:
If im on a specific site i want that some of javascript files to be loaded directly from my computer (f.e. file:///c:/test.js), not from the server.
For that i was thinking if there is a possibility to make an extension which could change HTML code in a response which browser gets right before displaying it. So whole process should look like that:
request is made
browser gets response from server
#response is changed# - this is the part when extension comes in
browser parse changed response and display page with that new response.
It doesnt even have to be a Chrome extension anyway. It should just do the job described above. It can block original file and serve another one (DNS/proxy?) or filter whole HTTP traffic in my computer and replace specific code to another one of matched response.
You can use the WebRequest API to achieve that. For example, you can add a onBeforeRequest listener and redirect some requests:
chrome.webRequest.onBeforeRequest.addListener(function(details)
{
var responseData = "<div>Some text</div>"
return {redirectUrl: "data:text/html," + encodeURIComponent(responseData)};
}, {urls: ["https://www.google.com/"]}, ["blocking"]);
This will display a <div> element with the text "some text" instead of the Google homepage. Note that you can only redirect to URLs that the web server itself is allowed to redirect to. This means that redirecting to file:/// URLs is not possible, and you can only redirect to files inside your extension if these are web accessible. data: and http: URLs work fine however.
In Windows you can use the Proxomitron (proxomitron.info) which is a local proxy that can intercept any page or file being loading into your browser and change it using regular expressions (no DOM parsing) however you want, before it is rendered by the browser.