【问题标题】:Cannot read properties of undefined (reading 'tabs')无法读取未定义的属性(读取“选项卡”)
【发布时间】:2022-06-19 02:39:35
【问题描述】:

我正在尝试构建一个 chrome 扩展,当点击 tabBtn 时它将获取当前 url。我收到一条错误消息Cannot read properties of undefined (reading 'tabs') 我已经在 vanilla JS 中使用了这个方法chrome.browser.tabs.query({currentWindow: true,active: true },(tabs) => {}) 没有任何问题,但是使用 React 它不起作用。我尝试将上述代码放在useEffect() 中,但错误未解决。我已经尝试了来自这个article 和这个post 的例子,不幸的是它已经解决了。

*** 错误信息现在阅读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"
}

【问题讨论】:

  • 删除browser.
  • 我现在收到错误消息“无法读取未定义的属性(读取 '查询')'
  • 我猜你从本地主机或文件打开你的页面:URL。您应该单击工具栏中的扩展图标。另请注意,弹出窗口是一个单独的窗口,因此它有自己单独的开发工具。
  • 在 google chrome 扩展程序中,我现在收到此错误 'Uncaught TypeError: window.chrome.query is not a function'
  • 您可能看到了一个旧错误。如上所述使用弹出窗口的开发工具。

标签: reactjs google-chrome-extension


【解决方案1】:

我今天也遇到了同样的情况。事实证明,chrome.tabs.query 不能在内容脚本中使用。文档:

Additionally, content scripts cannot use tabs.query

或者,如果你想实现这一点,你可以在内容脚本中发送消息:

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);
      });
    }
  })

并在background.js中查询标签ID:

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;
});

这个例子比你需要的稍微复杂一点,但是基本的要求已经满足了。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-09-08
    • 1970-01-01
    • 2020-01-29
    • 2020-01-08
    • 1970-01-01
    • 2023-03-11
    • 2022-01-15
    • 2021-12-31
    相关资源
    最近更新 更多