如何从chrome扩展程序弹出窗口打开新选项卡

时间:2012-10-31 10:07:17

标签: javascript google-chrome google-chrome-extension

我是Chrome扩展程序的新手。我尝试了第一个示例练习来创建扩展。现在我尝试在扩展弹出窗口的新选项卡中打开一个URL。 我刚在popup.html页面添加了一个HTML锚标记。

a href="www.google.com">Click</a>

但它没有开放。它试图在弹出窗口中打开带有以下URL的URL。

铬扩展://ljamgfaclheagbikmcagffcbdbcoodna/www.google.com

我的popup.html有这段代码。

<!doctype html>
<html>
  <head>
    <title>Getting Started Extension's Popup</title>
    <style>
    </style>
    <!-- JavaScript and HTML must be in separate files for security. -->
     </head>
  <body>
  <b>Karthick</b>
  <a href="www.google.com">Click</a>
  </body>
</html>

我的Manifest.json有以下JSON

{
  "name": "Test Extension",
  "version": "1.0",
  "manifest_version": 2,
  "description": "The first extension for my test",
  "browser_action": {
    "default_icon": "icon.png",
    "default_popup": "popup.html"
  },
  "permissions": [
    "tabs"
  ]
}

我没有在popup.js中写过任何东西 我搜索了它是如何做到的。但他们说我必须使用以下内容。

chrome.tabs.getSelected({}, function(tab) {
  chrome.tabs.update(tab.id, {url: 'http://google.com'});
});

但我不知道正确的方式/在哪里做。请告诉我这样做的步骤。 提前谢谢。

3 个答案:

答案 0 :(得分:2)

您可以为链接添加onclick-listener。

var link = document.getElementById("link");
link.addEventListener("click", function(){
  chrome.tabs.getSelected({}, function(tab) {
    chrome.tabs.update(tab.id, {url: 'http://google.com'});
  });
}, false);

但是我会使用chrome.tabs.create()函数。

答案 1 :(得分:2)

这是解决方案,只需将以下代码添加到popup.js:

$(function() {
  $('#s').click(function() {
     chrome.tabs.create({url: 'http://www.google.com'});
  });
});

document.addEventListener('DOMContentLoaded');

并更新您的锚标记,如下所示:

<a id="s" href="www.google.com">Click</a>

因为我们使用jquery选择器将popup.html更新为:

<!doctype html>
<html>
  <head>
    <style>
    </style>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
    <script src="popup.js"></script>
  </head>
  <body>
  <b>Karthick</b>
  <a href="www.google.com">Click</a>
  </body>
</html>

并允许popup.html中的jquery更新您的清单,如下所示:

{
  "name": "Test Extension",
  "version": "1.0",
  "manifest_version": 2,
  "description": "The first extension for my test",
  "browser_action": {
    "default_icon": "icon.png",
    "default_popup": "popup.html"
  },
  "permissions": [
    "tabs"
  ],  //<<--- do not miss this ","
  "content_security_policy": "script-src 'self' https://ajax.googleapis.com; object-src 'self'"
}

如果这不起作用,lemme会发送给你的crx。 干杯!

答案 2 :(得分:2)

Easy.将其放入popup.html:

<a href='google.com' target='_newtab'>Click</a>

或者把它放在JS文件中:

window.open('http://google.com','_newtab');

相关问题