简体   繁体   中英

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

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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