Home > Back-end >  chrome extension to open in new tab instead of popup
chrome extension to open in new tab instead of popup

Time:11-09

I am trying to get some data from current tab to my extension. It's working fine if I change it to popup style but I am looking for the same functionality to open it in a new tab on extension click. Can anybody guide on this how I can achieve this? Thanks in advance

manifest.json.js

{
    "manifest_version": 2,

    "name": "Hello World",
    "description": "A simple page-scraping extension for Chrome",
    "version": "1.0",
    "author": "@thomasforth",

    "background": {
        "scripts": ["popup.js"],
        "persistent": true
    },

    "permissions": [
        "tabs",
        "http://*/",
        "*://*/",
        "activeTab"
    ],
    "browser_action": {
        "default_icon": "logo.png"
        
    }
}

payload.js

// send the page title as a chrome message
chrome.runtime.sendMessage(document.title);
console.log(document.title)

popup.js

// Inject the payload.js script into the current tab after the popout has loaded
window.addEventListener('load', function (evt) {
    chrome.extension.getBackgroundPage().chrome.tabs.executeScript(null, {
        file: 'payload.js'
    });;
});

// Listen to messages from the payload.js script and write to popout.html
chrome.browserAction.onClicked.addListener(function (tab) {
    chrome.tabs.create({ url: "popup.html", selected: false })
    chrome.runtime.onMessage.addListener(function (message) {
    
    document.getElementById('pagetitle').innerHTML = message;
    
})
})

This the is error which I am getting

This the is error which I am getting

CodePudding user response:

Use the id of the tab where onClicked was triggered and pass it to popup script using its URL:

chrome.browserAction.onClicked.addListener(function (tab) {
  chrome.tabs.create({
    url: `popup.html?tabId=`   tab.id,
    selected: false,
  });
});

// popup.js

const tabId =  new URLSearchParams(location.search).get('tabId');
chrome.tabs.executeScript(tabId, {
  file: 'payload.js'
});
  • Related