Opening a new tab in the Google Chrome Extension

This is my background.html file, it works fine when opened in the current tab, but I want it to open in a new tab, what am I doing wrong?

<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> 
+4
source share
3 answers

You should read the chrome.tabs.create documentation again. You pass invald parameters to it. You also use location , which is from the background.html document, and not the web page document that expects the code, instead of the tab parameter passed to the chrome.browserAction.onClicked listener.

 <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> 
+6
source

You can try this

 <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> 
+1
source
 <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> 

If you insist on using a popup and want it to close as soon as it is open, use the above. Just add the link bar and true boolean to the master.newtab function master.newtab that it opens a new tab and then closes the popup.

If you change your mind about closing the popup, you can replace true boolean with a function to execute if a new tab was created without any errors. You can also use the master.link function to call the master.newtab function from the binding element.

The best thing about using Chrome Extensions is that you never have to worry about support issues !: D

0
source

Source: https://habr.com/ru/post/1385658/


All Articles