How to send POST request from chrome extension (without clicking) to Flask when browser is reloading the page?

早过忘川 提交于 2019-12-14 03:44:38

问题


I want to merge the snippets below to be able to send post request (containing URL) from chrome extension to flask whenever the page in Chrome is loading without clicking the extension' icon. Is this possible? Moreover I would like the popup to be shown only on specific pages that I declare (I believe there is a way ('matches') for this in manifest.json however, I don't know how to implement this.)

chrome.tabs.query({
active: true,
lastFocusedWindow: true
}, function(tabs) {
var tab=tabs[0];
    console.log(tab.url);
var xhr = new XMLHttpRequest();
    xhr.addEventListener("readystatechange", function () {
    if (xhr.readyState == 4) {
        console.log(xhr.responseText);
        alert(xhr.responseText)
  }
});
    xhr.open("POST", "http://localhost:5000/",true);
    xhr.send(tab.url); 
});

This script allows me to send post request on click, however I need to do this without clicking. I found also such a script that displays all information about change in browser content in down-right corner:

 chrome.tabs.onUpdated.addListener(function(tabId, changeInfo, tab) {
 alert(changeInfo.url);
 console.log(changeInfo.url);

I tried to merge these two, but with no result. I'm kind of newbie to JS and Chrome Extensions, so I would be duty grateful for your help.

After reaching this point I would like to be able to show popup conditionally, this is only when the specific page will be loaded, so I would appreciate your further hints.


回答1:


You can use chrome.webNavigation.onCommitted and specify a list of URLs to monitor.
The code below uses console.log so the output is shown in the background console.

manifest.json:

{
  "name": "test",
  "version": "0.0.1",
  "manifest_version": 2,
  "background": {
    "scripts": [
      "background.js"
    ],
    "persistent": false
  },
  "permissions": [
    "webNavigation",
    "http://localhost/"
  ]
}

background.js:

chrome.webNavigation.onCommitted.addListener(onCommitted, {
  url: [
    {hostEquals: 'www.example.org'},
    {urlPrefix: 'https://example.org/'},
    {urlMatches: '^https://(www\\.)?example.org/.*$'},
  ],
});

function onCommitted(info) {
  const xhr = new XMLHttpRequest();
  xhr.onload = () => {
    console.log('%d:%d', info.tabId, info.frameId, info.url, xhr.responseText);
  };
  xhr.open('POST', 'http://localhost:5000/');
  xhr.send(info.url);
}


来源:https://stackoverflow.com/questions/53884404/how-to-send-post-request-from-chrome-extension-without-clicking-to-flask-when

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!