问题
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?
回答1:
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?
来源:https://stackoverflow.com/questions/54005443/displaying-post-response-xmlhttprequest-in-chrome-extension-pop-up-apart-from