Html Chrome 扩展程序:如何在新标签页中打开链接?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16503879/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 08:19:07  来源:igfitidea点击:

Chrome extension: How to open a link in new tab?

javascripthtmlgoogle-chromegoogle-chrome-extensiontabs

提问by Tuyen Pham

In my Stackoverflow folder, I have stackoverflow.icoand 2 bellow files. When importing it to Chrome, it shows the icon in address bar, but when I click on it, Chrome doesn't open any new tab. What am I doing wrong?

在我的 Stackoverflow 文件夹中,我有stackoverflow.ico2 个波纹管文件。将其导入 Chrome 时,它​​会在地址栏中显示图标,但是当我单击它时,Chrome 不会打开任何新标签页。我究竟做错了什么?

manifest.json

清单文件.json

{
  "name": "Stackoverflow",
  "version": "1",
  "browser_action":
  {
    "default_icon": "stackoverflow.ico"
  },
  "background":
  {
    "page": "index.html"
  },
  "permissions": ["tabs"],
  "manifest_version": 2
}

index.html

索引.html

<html>
  <head>
    <script>
      chrome.browserAction.onClicked.addListener(function(activeTab)
      {
        var newURL = "http://stackoverflow.com/";
        chrome.tabs.create({ url: newURL });
      });
    </script>
  </head>
</html>

回答by BeardFist

The problem is that you are violating manifest version 2's content security policy. To fix it all you have to do is get rid of inline script, in this case your background page. Turn it into a background scriptlike this:

问题是您违反了清单版本 2 的content security policy. 要修复它,您所要做的就是摆脱内联脚本,在这种情况下,您的背景page. 把它变成这样的背景script

manifest.json

清单文件.json

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

background.js

背景.js

chrome.browserAction.onClicked.addListener(function(activeTab){
  var newURL = "http://stackoverflow.com/";
  chrome.tabs.create({ url: newURL });
});

If, for some reason, you do need it to be a page, then simply include the script as an external file and declare it as a page like before.

如果出于某种原因,您确实需要将其作为页面,那么只需将脚本作为外部文件包含并像以前一样将其声明为页面。

回答by ego

In my case I needed to open link in a new tab when I clicked a link within extension popup window, it worked fine with targetattribute set to _blank:

在我的情况下,当我单击扩展弹出窗口中的链接时,我需要在新选项卡中打开链接,target属性设置为_blank

<a href="http://www.example.com" target="_blank">Example</a>

回答by fvrab

I would prefer simpler solution- just add action to onclick

我更喜欢更简单的解决方案- 只需向 onclick 添加操作

$('body').on('click', 'a[target="_blank"]', function(e){
    e.preventDefault();
    chrome.tabs.create({url: $(this).prop('href'), active: false});
    return false;
});

This will open all links (even links that were dynamically created) that have target="_blank" attribute in a new tab without loosing popup focus.

这将在新选项卡中打开所有具有 target="_blank" 属性的链接(甚至是动态创建的链接),而不会失去弹出焦点。