1

I'm attempting to build a chrome extension that will grab the current url when tabBtn is clicked. I am receiving an error messageCannot read properties of undefined (reading 'tabs') I've used this method chrome.browser.tabs.query({currentWindow: true,active: true },(tabs) => {}) in vanilla JS without any issues but using React its not working. I've tried placing the above code in useEffect() but the error is unresolved. I've tried examples from this article and this post which was unfortunately resolved.

*** error message now read Cannot read properties of undefined (reading 'query')

/*global chrome*/

import {useEffect, useState} from 'react';
import {TabBtn} from "./components/Buttons"


function App() {
 
 
/*  useEffect(()=>{ 
      chrome.tabs.query(
         { currentWindow: true, active: true },
         (tabs) => {
           // setMyLeads((prev) => [...prev, 
         tabs[0].url]);
           console.log(tabs[0].url);
         }
       );
    
  },[]) */


  const tabBtn = () => {
       chrome.tabs.query(
         { currentWindow: true, active: true },
         (tabs) => {
        
           console.log(tabs[0].url);
         }
       );
  }

 
  return (
    <main>
    
      <TabBtn tabBtn={tabBtn} />

    </main>
  );
}

export default App

manifest.json

{
    "name": "chrome extension app",
    "version": "1.0",
    "manifest_version": 3,
     "permissions": [
        "activeTab",
        "storage",
        "tabs"
    ],
    "action": {
        "default_popup": "index.html"
    },
    "default_icon": "/img/icon.png"
}
user3574939
  • 819
  • 3
  • 17
  • 34

1 Answers1

1

I got into the same situation today. It turns out that chrome.tabs.query cannot be used in the content script. The doc:

says Additionally, content scripts cannot use tabs.query.

Alternatively, if you want to achieve this, you can send a message in the content script:

document.onmouseup = function() {
  chrome.runtime.sendMessage({msgType: "queryTabId"}, function(response) {
    var _tabId = response.tabId;
    console.log('current tab id:' + _tabId);
    if(_tabId){
      var _SELECTION = {_tabId: ''};
      _SELECTION._tabId = window.getSelection()?.toString() ?? '';
      chrome.storage.local.set(_SELECTION, function() {
          console.log('Selection saved: ', _SELECTION._tabId);
      });
    }
  })

and query tab id in background.js:

chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
  console.log("background received message: " + message);
  if (message.msgType === 'queryTabId') {
    chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
      sendResponse({tabId: tabs[0].id});
    });
  }
  // https://stackoverflow.com/a/56483156/9304616
  return true;
});

The example is a little more complex than your need, but the basic requirement is satisfied.

Lebecca
  • 2,406
  • 15
  • 32