简体   繁体   English

不会在弹出窗口中触发chrome.tabs.create的回调吗?

[英]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. 我正在编写第一个chrome扩展程序,该扩展程序应在新标签页中打开一个URL,然后执行某些操作。

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: 的script.js:

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

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

popup.html: 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. 问题是打开URL后没有任何反应。 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. 弹出窗口关闭时,其JavaScript上下文被破坏,没有回调可调用。

You have 2 options: 您有2个选择:

  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). 但是,这不仅会导致标签页无法聚焦-Chrome不会切换到该标签页(在后台打开它)。 Might not be what you want. 可能不是您想要的。 You can switch after your other operations are done though - with chrome.tabs.update to set active: true . 不过,您可以在完成其他操作后进行切换-使用chrome.tabs.updateactive: true设置为active: true

Note that there is no way for a popup to survive focus loss, this is by design. 请注意,弹出窗口无法克服焦点丢失,这是设计使然。

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

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