[英]Chrome extension: How to open a link in new tab?
In my Stackoverflow folder, I have stackoverflow.ico
and 2 bellow files.在我的 Stackoverflow 文件夹中,我有
stackoverflow.ico
和 2 个波纹管文件。 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.将其导入 Chrome 时,它会在地址栏中显示图标,但是当我单击它时,Chrome 不会打开任何新标签页。 What am I doing wrong?
我究竟做错了什么?
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>
The problem is that you are violating manifest version 2's content security policy
.问题是您违反了清单版本 2 的
content security policy
。 To fix it all you have to do is get rid of inline script, in this case your background page
.要修复它,您所要做的就是摆脱内联脚本,在这种情况下是您的背景
page
。 Turn it into a background script
like this:把它变成这样的后台
script
:
manifest.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.如果出于某种原因,您确实需要将其作为页面,那么只需将脚本作为外部文件包含并像以前一样将其声明为页面。
在我的情况下,当我单击扩展弹出窗口中的链接时,我需要在新选项卡中打开链接,它在target
属性设置为_blank
时工作正常:
<a href="http://www.example.com" target="_blank">Example</a>
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" 属性的链接(甚至是动态创建的链接),而不会失去弹出焦点。
You do not need jQuery.你不需要jQuery。 Just use
window.open("http://example.com", "_blank")
.只需使用
window.open("http://example.com", "_blank")
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.