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

前端 未结 3 1611
隐瞒了意图╮
隐瞒了意图╮ 2020-12-07 13:03

In my Stackoverflow folder, I have stackoverflow.ico and 2 bellow files. When importing it to Chrome, it shows the icon in address bar, but when I click on it,

相关标签:
3条回答
  • 2020-12-07 13:42

    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 script like this:

    manifest.json

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

    background.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.

    0 讨论(0)
  • 2020-12-07 13:45

    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 target attribute set to _blank:

    <a href="http://www.example.com" target="_blank">Example</a>
    
    0 讨论(0)
  • 2020-12-07 13:52

    I would prefer simpler solution - just add action to 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.

    0 讨论(0)
提交回复
热议问题