Chrome extension; open a link from popup.html in a new tab

前端 未结 9 605
挽巷
挽巷 2020-12-04 16:23

I\'m doing a Chrome extension and I got helped in this post here.

My problem now is how to open a new tab of chrome that has as URL the link I clicked in the

相关标签:
9条回答
  • 2020-12-04 16:58

    The other answers work. For completeness, another way is to just add target="_blank"

    Or if you have want to "manually" add particular links, here's a way (based on the other answers already here):

    popup.html

    <a id="index_link">My text</a>.
    

    popup.js

    document.addEventListener('DOMContentLoaded', () => {
       var y = document.getElementById("index_link");
       y.addEventListener("click", openIndex);
    });
    
    function openIndex() {
     chrome.tabs.create({active: true, url: "http://my_url"});
    }
    
    0 讨论(0)
  • 2020-12-04 17:00

    You should use chrome.tabs module to manually open the desired link in a new tab. Try using this jQuery snippet in your popup.html:

    $(document).ready(function(){
       $('body').on('click', 'a', function(){
         chrome.tabs.create({url: $(this).attr('href')});
         return false;
       });
    });
    
    0 讨论(0)
  • 2020-12-04 17:01

    A bit more concise version in modern JS:

    document.addEventListener('DOMContentLoaded', function () {
      for (const anchor of document.getElementsByTagName('a')) {
        anchor.onclick = () => {
          chrome.tabs.create({active: true, url: anchor.href});
        };
      };
    });
    
    0 讨论(0)
  • 2020-12-04 17:05

    open with ctrl-click or middle-click

    $('body').on('click auxclick', 'a', e => {
        if (e.ctrlKey || e.button == 1) {
            e.preventDefault();
            chrome.tabs.create({ url: e.currentTarget.href, selected: false});
        }
    });
    
    0 讨论(0)
  • 2020-12-04 17:06

    If you don't want to use JQuery, insert this into your popup.js and it will make all your links open in a new tab when clicked

    Remember to declarer the "tabs" permission in the manifest.json

    window.addEventListener('click',function(e){
      if(e.target.href!==undefined){
        chrome.tabs.create({url:e.target.href})
      }
    })
    
    0 讨论(0)
  • 2020-12-04 17:16

    A bit more concise and actual syntax in 2020:

    document.addEventListener('DOMContentLoaded', () => {
      const links = document.querySelectorAll("a");
    
      links.forEach(link => {
        const location = link.getAttribute('href');
        link.addEventListener('click', () => chrome.tabs.create({active: true, url: location}));
      });
    });
    
    0 讨论(0)
提交回复
热议问题