[英]How to download file in google chrome extension without opening a new tab
[英]Opening a new tab on Google Chrome Extension
这是我的 background.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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.