Invocation of form tabs.connect(undefined, object) doesn't match definition?

匿名 (未验证) 提交于 2019-12-03 01:40:02

问题:

I'm making a simple chrome extension and need to have my popup page connect to the content script on the current tab. However it keeps giving me an error for the tabId argument to tabs.connect. It's saying the tab id I'm passing is undefined rather than an integer. I have no idea why.

Full Error:

Uncaught Error: Invocation of form tabs.connect(undefined, object) doesn't match definition tabs.connect(integer tabId, optional object connectInfo)     at Object.normalizeArgumentsAndValidate (extensions::schemaUtils:115)     at Object.<anonymous> (extensions::binding:363)     at connectToCurrentTab (popup.js:21)     at HTMLDocument.<anonymous> (popup.js:44)     at mightThrow (jquery-3.2.1.js:3583)     at process (jquery-3.2.1.js:3651) 

I made a short function to retrieve the current tab id:

function getCurrentTabId() {     var query = {active: true, currentWindow: true};      var tabId;      chrome.tabs.query(query, function (tabArray) {         tabId = tabArray[0].id;          console.log("Tab id: " + tabId);     });      return tabId; } 

It appears to be getting the correct tab id or at least an integer. Console out put: Tab id: 111

I use the current tab id retrieved by getCurrentTabId to chrome.tabs.connect from my popup to the content script running on the current tab then return the Port it connected on.

function connectToCurrentTab () {     var currentTabId = getCurrentTabId();      return chrome.tabs.connect(currentTabId, {name: "popup"}); //<-- error thrown here } 

Any help or information is much appreciated.

回答1:

Your code is almost correct, the problem it's than chrome.tabs.query is async method. So, at the moment when you call chrome.tabs.connect - currentTabId it's undefined.

You can fix it with usage of callback function:

function getCurrentTabId(cb) {     var query = {active: true, currentWindow: true};     chrome.tabs.query(query, function (tabArray) {         console.log("Tab id: " + tabArray[0].id);         cb(tabArray[0].id)     }); }  function connectToCurrentTab () {     getCurrentTabId(function(currentTabId) {        chrome.tabs.connect(currentTabId, {name: "popup"})     }); } 

You can also use a Promise to prevent a callbacks hell.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!