[英]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.