Chrome Extension interact with page (not in tab) in background - javascript

How can I make a extension that interact with a page in background (not in tab)? for example check www.google.com each 5 minutes while I have only www.yahoo.com open.
I have made the function of the extension but I need to know how to use it without having this page open.
Regards.

Saying you want to interact with https://www.google.com without opening it, you could make an ajax call in background page. Steps would be like the following:
Add https://www.google.com/* in permissions field in manifest.json
"permissions": ["https://www.google.com/*"]
Make an ajax call in background page.
var xhr = new XMLHttpRequest();
xhr.onload = function() {
var data = xhr.responseText;
// Your logic to handle response data
};
xhr.open("GET", "https://www.google.com");
xhr.send();

Related

Debug javascript from a generated page

In my application I made some computing server side with a Javascript interpreter. I'd like to take advantage from F12 debug engine in my browser chroome to let the user debug his scripts. To do that a generare a new page and open it in a new window
var xhttp = new XMLHttpRequest();
xhttp.open("POST", "/test/tipoManufatto", true);
xhttp.setRequestHeader("Content-Type", "application/json");
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var new_window = window.open(null, '');
new_window.document.write(this.responseText);
}
};
xhttp.send(JSON.stringify($scope.tc.selected));
the page is generated correctly and the server side generated scripts runs fine but if get into F12 tools
I cannot see my script in the source tab therefore I cannot set any breakpoints.
Is there a better way to open a dynamically generated page in a new window? I need to generate the page from the back-end with a POST verb in order to send some data.
Here is what my network tabs looks like

Detecting start and stop of xhr request

I'm using a wysiwyg editor called summernote. This editor exists as an iframe within my application.
The editor accepts images and upon inserting an image into the editor, the image automatically starts to upload to my s3 bucked on aws. I've looked at the source code for django-summernote and I can't seem to see any references to ajax, so I'm not sure if it uses that or another technology.
What I do know is that during the upload process, an xhr request in initiated and remains active for the duration of the upload.
As soon as the user drops an image in the editor (and the xhr request starts), I'd like to show a spinner/loading icon so that they are aware that something is happening. I'd like the spinner to disappear once the xhr request has completed.
Is there a way that I can have javascript listen for any xhr requets and fire an event when one starts and when it ends?
Thanks!
Edit: Paul has indicated that I can use these:
var xhr = new XMLHttpRequest();
console.log('UNSENT', xhr.readyState); // readyState will be 0
xhr.open('GET', '/api', true);
console.log('OPENED', xhr.readyState); // readyState will be 1
xhr.onprogress = function () {
console.log('LOADING', xhr.readyState); // readyState will be 3
};
xhr.onload = function () {
console.log('DONE', xhr.readyState); // readyState will be 4
};
xhr.send(null);
Do I need to poll for the XMLHTTPRequest() every second and then check its status or is there a cleaner way to do this?
Thanks!

Displaying post response (XMLHttpRequest) in chrome extension pop-up apart from python console

I am creating chrome extension that is sending post request with information about specific url that is currently browsed by user to flask (local host) and then some web scraping on this url is done and based on the obtained information a category is assigned. After this process is done I would like the popup to show assigned category when user is on page(s) declared earlier (ofc without user action e.g. clicking on extension icon). At the moment I see this happening on python console but I'm not able to see this on popup which appears blank (I presume that this is because the script needs about 1-3 seconds to perform and listener or some kind of timeout is needed to reach my goal, however I'm total JS newbie at the moment and I cant find right solution). When I click 'ok' on the popup then I see that on the background.js in dev tools there is information that I am looking for. However I need to have this on the popup. How can I do this? I described my goal and actions that are taken on the image below -
https://imgur.com/a/8Jknf1r
Code that I use (background.js) with stackoverflow as exemplary page looks like this:
function onCommit(info) {
const xhr = new XMLHttpRequest();
xhr.onload = () => {
console.log('onload %d:%d', info.tabId, info.frameId, info.url);
};
xhr.open('POST', 'http://localhost:5000/',true);
xhr.send(info.url);
// xhr.addEventListener("readystatechange", function () {
console.log(xhr.responseText);
alert(xhr.responseText);
}};
chrome.webNavigation.onCommitted.addListener(onCommit, {
url: [
{hostEquals: 'www.stackoverflow.com'},
{urlPrefix: 'https://stackoverflow.com/'},
{urlMatches: '^https://(www\\.)?stackoverflow.com/.*$'},
],
});
alert(xhr.responseText) at the moment results in blank popup - what to do to fill it with response?
Ok I figured it out, just typical newbie error concerning syntax near listener; code that works:
function onCommit(info) {
const xhr = new XMLHttpRequest();
xhr.onload = () => {
console.log('onload %d:%d', info.tabId, info.frameId, info.url);
};
xhr.open('POST', 'http://localhost:5000/',true);
xhr.send(info.url);
xhr.addEventListener("readystatechange", function () {
console.log(xhr.responseText);
alert(xhr.responseText);
})
};
chrome.webNavigation.onCommitted.addListener(onCommit, {
url: [
{hostEquals: 'www.stackoverflow.com'},
{urlPrefix: 'https://stackoverflow.com/'},
{urlMatches: '^https://(www\\.)?stackoverflow.com/.*$'},
],
});
One issue that is strange for me is that the popup now appears 3 times, first blank, then click ok, I've got an answer (which was expected) and then after clicking again it appears again - is it specific or may I change that?

XMLHttpRequest not sent if web page location is changed afterwards

At some point my webpage is changing its location.href, resulting in the browser navigating to another page.
I would like to do a XHR POST request just before changing the page.
I would rather not wait for this XHR request completion, because not receiving 100% of the requests is OK but speed is paramount.
I tried this code, however the XHR request is NOT send by Firefox/Chrome, because of the location.href change right after.
<html>
<head></<head>
<body>
This is page test1.htm<br>
<input type="button" value="Go!" onclick="go();">
<script>
function go() {
xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() { /* Do nothing */ };
xhr.open('POST', '/cgi-bin/hb.exe?action=remoteapppost', true);
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xhr.send('action=remoteapppost&id=TEST');
// ==> this XHR request is NOT sent because of the following line:
location.href = "test2.htm";
}
</script>
</body>
</html>
If I do a breakpoint or move the location.href = "..."; inside the callback, everything is working fine (of course).
Any idea on how to send a XHR request just before leaving a webpage?
You want to use a combination of the beforeunload event and the new navigator.sendBeacon() API that's designed to not block navigation.

Reload iframe only when iframe contents are new?

Short version:
How could an HTML file that has an iframe pointing to another HTML file on the same server automatically reload that iframe whenever the iframe's content is new?
Context:
I'm using an HTML/Javascript file to watch for new instructions from a Python program. The Python program rewrites a simple HTML file when there are new instructions to see.
So my easy solution is a bit of Javascript that forces a reload of the iframe src every second.
However, this causes a flash of the content every time the iframe loads, and most of the time the information isn't new.
Instead, I'd prefer for the HTML file to only force a reload of the iframe src when it's new. Is this possible?
You can use an AJAX request to check if the iframe has changed.
var value;
(function check() {
var xhr = new XMLHttpRequest();
xhr.open('GET', '/url/toIframe'); // change this to the correct URL
xhr.addEventListener('load', function() {
if(value === undefined) {
value = this.responseText;
} else if(value != this.responseText) {
value = this.responseText;
// refresh iframe!
}
setTimeout(check, 1000); // check again in another second
});
xhr.send();
})();
This makes requests to the server to see if the content has changed. There is one second between each the end of a request and the start of the next check. (And currently, there is no error handling if the server goes down.)
FYI, if the server sends a Last-Modified header, you could actually make a HEAD request and just check that header. If you don't know what I am talking about, don't worry about it.

Categories

Resources