繁体   English   中英

浏览器重新加载页面时,如何从chrome扩展程序(无需单击)向flask发送POST请求?

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

我想合并下面的代码段,以便能够在Chrome加载页面时将Chrome扩展程序中的发布请求(包含URL)发送到Flask,而无需单击扩展程序图标。 这可能吗? 此外,我希望仅在我声明的特定页面上显示弹出窗口(我相信manifest.json中有一种方法(“匹配项”),但是,我不知道该如何实现。)

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); 
});

该脚本允许我在点击时发送帖子请求,但是我需要点击后发送。 我还发现了这样一个脚本,该脚本在右下角显示有关浏览器内容更改的所有信息:

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

我试图合并这两个,但没有结果。 我是JS和Chrome扩展程序的新手,因此,感谢您的帮助。

在达到这一点之后,我希望能够有条件地显示弹出窗口,这仅在特定页面将被加载时进行,因此,我感谢您的进一步提示。

您可以使用chrome.webNavigation.onCommitted并指定要监视的URL列表。
下面的代码使用console.log,因此输出显示在后台控制台中

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);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM