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

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.

Related

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

Add content of one page to another

Can i add the content part of this link into my webpage
http://rid3201.org/site/club_members2.php?id=MTk3Ng==
I want to avoid the header part.Can i use iframe or object for this.
Use Html Agility Pack
With it you can get the whole page and select only the html element you need (I assume it would be table).
Then you can pass it to your page.
If you own the domain rid3201.org, you can do it with jQuery:
$('#result').load('ajax/test.html #container');
heads up!
If are not the owner of the domain, you CAN'T do it via jQuery.
The documentation of .load() says:
Due to browser security restrictions, most "Ajax" requests are subject
to the same origin policy; the request can not successfully retrieve
data from a different domain, subdomain, or protocol.
An alternative to jQuery is using XMLHttpRequest, coding with a backend language, like .Net
After you catch the url source, you have to clean the code to get only the div you want.

HTML5 History API: JSON displayed when going "back" to another page, and then "forward" again

I have a page where there are several search / filter button which, when clicked, refresh the contents of a list below through AJAX.
In the process, I'm modifying history (through pushstate) so that the new filtered page is bookmarkable, and so the back button works. I'm also listening for the popstate event, to react to Back.
My code looks more or less like this:
window.addEventListener("popstate", function(ev) {
if (!window.history_ready) { return; } // Avoid the one time it runs on load
refreshFilter(window.location.href, true);
});
refreshFilter: function(newURL, backButtonPressed){
$.ajax({ url: newURL}).done( blah );
if (!backButtonPressed) {
window.history_ready = true;
history.pushState(null, null, newURL);
}
}
This works wonderfully, except for one weird case...
User is in page "A"
They click a link to go to this page that plays with history (let's call it "B")
They run a couple of filters, then press Back a few times, so they're back at the initial state of "B"
They click Back once again, which sends them back to "A"
At this time, if they press Forward, instead of making a request to the server again for Page "B", the browser simply displays a bunch of JSON code as the page contents (this JSOn is the response of one of my AJAX requests to filter stuff)
At least in latest Chrome
Why is this happening and how can I avoid it?
Chrome caches the pages you visit and when you go back or forward it uses the cache to display the page quickly. If the URLs you are using to retrieve JSON from the server by AJAX is the same one Chrome would hit, then it's possible Chrome is picking that page from the cache, which instead of being the nice HTML it's just a JSON dump.
There is a cache option for $.ajax:
$.ajax({ cache: false, url: newURL})
See http://api.jquery.com/jquery.ajax/
#pupeno is right, but to give a more solution oriented answer, you need to differentiate the JSON from HTML in the routes your server has.
I know two ways of doing this:
1) If you call /users you get HTML, if you call /users.json you get JSON.
2) If you call /users you get HTML, if you call /api/users you get JSON.
I like 1 a lot better, but it depends on the web framework if whichever is used by default or wether you configure that yourself.
1 is used in Ruby on Rails, 2 is used in other frameworks too.

HTML5 / JS / Offline mode - request for page with query parameters

I have a page which is part of Cache manifest (/cache).
As soon as my application is offline mode, I can open that page (http://app/cache). But if I try to access it with query string, Chrome treat it as Non-Existing and return fallback page (http://app/cache?url=1234 - does not work).
Does anyone know workaround for that?
I would use # - has tag to pass parameters. Like this:
http://app/cache#url/1234
Browsers ignores the hashtag, but your page javascript can parse and act on it.
It should be true that you will not be opening a page by tying the url on the browser. You will be clicking on a page to open the page. So on click call a Javascript function. Pass the querystring value to the function. save the querystring value to localstorage with a name.
When the page opens up read this value from localstorage on page load and get the value and use in your page.

Using AJAX and return a picture

I have a problem receiving and opening a picture via AJAX.
If I call the following page:
http://127.0.0.1:8889/ex?sql=SELECT+Image+FROM+Persons+WHERE+Number+Like+%27%2501%27
a picture is displayed from a blob field in IE8.
Now I would like to open this into a div after someone pressed a key (using AJAX)?
Trying to use xhr.responseText does not work (I get an error. Using it on a text response works). So it seems that my problem is to grab the result from the ajax request.
How can I do this?
Some code and the error message:
var picReturn = xhr.responseText;
=> Could not continue due to the following error: c00ce514
You have three options:
Place the resultant data in an iframe. Not very practical.
Take the result and place it in am image source as a data:uri. Not supported in older browsers and limited to 32/64Kb depending on the browser.
Skip the AJAX and write a web service and use that as your url. This is the best option.
You don't say what language you're using server-side but you essentially want to open a web response, set the header to "image/jpeg" and return your stream.