Chrome扩展:onclick扩展图标,在新选项卡中打开popup.html

quhf5bfb  于 2023-06-19  发布在  Go
关注(0)|答案(5)|浏览(151)

我创建了一个chrome扩展,并设法使用window.open打开popup.html文件。但是我想在一个新的标签页中打开它,我已经尝试了很多不同的方法,包括:

<script type="text/javascript" language="JavaScript">
  chrome.tabs.create('url': 'popup.html');

我只是把代码放在了错误的地方,还是完全错误的代码?

carvr3hs

carvr3hs1#

为什么要在新标签页中打开popup.html?您应该为此创建一个不同的页面。无论如何,如果你想打开popup.html,在一个新的选项卡中,你需要传入扩展名url。
http://code.google.com/chrome/extensions/extension.html#method-getURL

chrome.tabs.create({'url': chrome.extension.getURL('popup.html')}, function(tab) {
  // Tab opened.
});
bvjveswy

bvjveswy2#

现在你可以使用Event Pages在新标签页中打开popup.html,当扩展图标被点击时,不需要创建一个default_popup页面。
清单:

"background": {
    "scripts": ["background.js"],
    "persistent": false
}

js:

chrome.browserAction.onClicked.addListener(function(tab) {
    chrome.tabs.create({'url': chrome.extension.getURL('popup.html'), 'selected': true});
});
ovfsdjhp

ovfsdjhp3#

按照http://code.google.com/chrome/extensions/tabs.html中的说明使用chrome. tables.create(对象属性,函数回调)
对象属性可以包含windowId、index、url和selected字段。可选的回调函数接收新创建的选项卡的Tab对象。
因此,在当前窗口中创建一个新选项卡并将其选中的最简单示例如下所示:

chrome.tabs.create({'url': chrome.extension.getURL('popup.html')});

不知道为什么你想在一个新的选项卡中显示popup.html,但我发现它在开发/调试我的扩展时非常有用。在扩展页面上“通常”只有一个到背景页面的链接,这是相当痛苦的。
会很想知道如何在一个新窗口中打开它,也许在一个信息亭模式;- )

cig3rfwq

cig3rfwq4#

一个完整的工作示例:

Manifest.json

{
  "manifest_version": 2,
  "name": "HelloWorld",
  "version": "0.0.1",
  "description": "This is HelloWorld",
  "author": "BaiJiFeiLong@gmail.com",
  "browser_action": {
  },
  "background": {
    "scripts": [
      "background.js"
    ]
  }
}

background.js

// Created by BaiJiFeiLong@gmail.com at 2022/4/13

chrome.browserAction.onClicked.addListener(async () => {
    await chrome.tabs.create({url: chrome.extension.getURL("popup.html")});
})

popup.html

<!--Created by BaiJiFeiLong@gmail.com at 2022/4/13-->

<body style="min-width: 500px">
<h1>Hello World</h1>
</body>
jucafojl

jucafojl5#

Manifest v3,2023

大多数答案可能不会与manifest v3一起工作;很多API都随着更新而改变了。这是@BaijiFeiLong的答案的更新版本,将在v3中工作:

manifest.json

{
  "manifest_version": 3,
  "name": "My nice little extension",
  "description": "Just an example",
  "version": "0.0.1",
  "action": {},
  "background": {
    "service_worker": "background.js"
  },
}

background.js

chrome.action.onClicked.addListener(async () => {
  await chrome.tabs.create({ url: chrome.runtime.getURL("popup.html") });
});

popup.html

<body>
  <h1>Hello from my extension!</h1>
</body>

相关问题