不会在弹出窗口中触发chrome.tabs.create的回调吗? [英] Callback of chrome.tabs.create is not triggered in a popup?

查看:57
本文介绍了不会在弹出窗口中触发chrome.tabs.create的回调吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写我的第一个chrome扩展程序,该扩展程序应在新标签页中打开一个URL,然后执行某些操作.

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

清单:

{
  "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>

问题是打开URL后没有任何反应.可能是什么问题?

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

推荐答案

创建新标签时,默认情况下它会打开焦点,并导致弹出窗口关闭.弹出窗口关闭时,其JavaScript上下文被破坏,没有回调可调用.

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.

您有2个选择:

  1. 将逻辑移至背景/消息来执行此操作,而不是从弹出窗口中打开该标签为你.

  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.

指定您要不专心地打开标签:

Specify that you want to open the tab unfocused:

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

但是,这不仅会导致标签页无法聚焦-Chrome不会切换到该标签页(在后台打开它).可能不是您想要的.不过,您可以在完成其他操作后进行切换-使用 chrome.tabs.update 设置 active:true .

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.

这篇关于不会在弹出窗口中触发chrome.tabs.create的回调吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆