【问题标题】:Chrome Extension: Close Window After XHRChrome 扩展:XHR 后关闭窗口
【发布时间】:2015-06-09 17:27:37
【问题描述】:

当用户单击按钮时,我想从 chrome 扩展中创建一个 XHR。然后我想关闭窗口。

如果我在发送后关闭窗口,请求将被取消。如果我关闭请求侦听器中的窗口,扩展程序将崩溃。

如何关闭窗口?

var requestListener = function() {
  bkg.console.log(this.readyState);
  window.close() // <-- When I put this here, the extension crashes.
};

document.addEventListener('DOMContentLoaded', function() {
  var button = document.getElementById('button');
  button.addEventListener('click', function() {
    var data = {foo: "bar"};
    var xhr = new XMLHttpRequest();
    xhr.open("post", "@987654321@", true);
    xhr.setRequestHeader("Content-Type", "application/json");
    xhr.onreadystatechange = requestListener;
    xhr.send(JSON.stringify(data));
    window.close(); // <-- When I put this here, the request is canceled.
  });
});

【问题讨论】:

  • 您的代码不会让我崩溃。但是我收到了这个警告:Scripts may close only the windows that were opened by it. 你可以向后台发送消息,从那里你可以运行chrome.tabs.remove( sender.tab.id, ...)
  • 看到这个错误需要什么?我无法在控制台中显示错误消息。
  • 我正在使用最新的 Chrome(版本 41.0.2272.118 m)并且刚刚在内容脚本中使用您的代码创建了测试扩展。是的,这个警告在目标页面的控制台中。

标签: javascript google-chrome-extension xmlhttprequest


【解决方案1】:

一个疯狂的猜测:也许窗口关闭得太快了,所以......

<body onbeforeunload="SendFunction();">

...可能会有所帮助。祝你好运。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多