Callback of chrome.tabs.create is not triggered in a popup?

戏子无情 提交于 2021-02-19 05:57:08

问题


I am writing my first chrome extension, which should open an URL in a new tab and after that do something.

manifest:

{
  "manifest_version": 2,

  "name": "Test",
  "description": "",
  "version": "1.0",

  "browser_action": {
    "default_icon": "icon.png",
    "default_popup": "popup.html"
  },
  "permissions": [
    "tabs",
    "activeTab"
  ]
}

script.js:

function toggle() {
        chrome.tabs.create({ url: "http://google.com" }, function(tab) {
        alert("Hello!");
        });
 }

document.getElementById('toggle').addEventListener('click', toggle);

popup.html:

<html>
  <head>
  </head>
  <body>
    <div id="toggle" class="clickable">START</div>
    <script type="text/javascript" src="script.js"></script>
  </body>
</html>

The problem is that nothing happens after the URL is opened. What can be the problem?


回答1:


When you create a new tab, by default it opens focused, and that causes the popup to close. When the popup closes, its JavaScript context is destroyed and there's no callback left to call.

You have 2 options:

  1. Move logic to the background/event page, which will survive the popup being closed. For example, instead of opening the tab from the popup, you can message the background page to do it for you.

  2. Specify that you want to open the tab unfocused:

    chrome.tabs.create(
      {
        url: "http://google.com",
        active: false 
      }, function(tab) {
        /* ... */
      }
    );
    

    However, this won't simply cause the tab to not focus - Chrome won't switch to it (opening it in the background). Might not be what you want. You can switch after your other operations are done though - with chrome.tabs.update to set active: true.

Note that there is no way for a popup to survive focus loss, this is by design.



来源:https://stackoverflow.com/questions/37089887/callback-of-chrome-tabs-create-is-not-triggered-in-a-popup

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