在谷歌浏览器扩展程序上打开一个新标签

Opening a new tab on Google Chrome Extension

本文关键字:一个 谷歌浏览器 新标签 标签 程序上 扩展      更新时间:2023-09-26

这是我的背景.html文件,在当前选项卡中打开时工作正常,但我希望它在新选项卡中打开,我做错了什么?

<html>
<head>
<script>
  // Called when the user clicks on the browser action.
  chrome.browserAction.onClicked.addListener(function(tab) {
    var action_url = "javascript:location.href='http://www.reddit.com/submit?url='+encodeURIComponent(location.href)+'&title='+encodeURIComponent(document.title)";
    chrome.tabs.create(tab.id, {url: action_url}, function(tab));
  });
</script>
</head>
</html>

您应该再次阅读chrome.tabs.create文档。您正在向它传递 invald 参数。您还使用来自background.html文档而不是代码期望的网页文档的location,而不是传递给chrome.browserAction.onClicked侦听器的tab参数。

<html>
<head>
<script>
  // Called when the user clicks on the browser action.
  chrome.browserAction.onClicked.addListener(function(tab) {
    var action_url = "http://www.reddit.com/submit?url=" + encodeURIComponent(tab.href) + '&title=' + encodeURIComponent(tab.title);
    chrome.tabs.create({ url: action_url });
  });
</script>
</head>
</html>
你可以

试试这个

<html>
...
<body>
    <script>
    function createTab() {
        chrome.tabs.create({url: "http://www.stackoverflow.com"});
    }
    </script>
    <a href="#" onclick="createTab();">Create a new tab</a>
</body>
</html>
<html>
 <head>
  <script type="text/javascript">
   window.master = ({
     newtab: function(url, callback) {
       callback = callback === true ? (function() { this.close(); }) : callback;
       try {
         chrome.tabs.create({
           url: url
         });
         if(typeof callback === "function") { callback.call(this, url); }
       } catch(e) {
         /* Catch errors due to possible permission issues. */
       }
     },
     link: function(event, close) {
       event = event ? event : window.event;
       event.preventDefault();
       this.newtab(event.href, close);
     },
     close: function() { window.self.close(); }
   });
  </script>
 </head>
 <body>
  <!-- Usage is simple:
        HTML:
         <a href="http://example.com/" onclick="master.link(event)" />
        JavaScript:
         master.newtab("http://example.com/", true);
  -->
 </body>
</html>

如果您坚持使用弹出窗口并希望它在打开后立即关闭,请使用上面的内容。只需将链接字符串和true布尔值添加到 master.newtab 函数,即可使其打开新选项卡,然后关闭弹出窗口。

如果您改变主意关闭弹出窗口,则可以将true布尔值替换为要执行的函数(如果创建新选项卡没有任何错误(。还可以使用 master.link 函数从锚元素调用 master.newtab 函数。

使用Chrome扩展程序最好的事情是,您永远不必担心支持问题! :D