简体   繁体   English

循环中的更新选项卡在 Chrome 扩展扩展中不起作用

[英]Update tab in Loop Not Working in Chrome Extension Extension

I am trying to build a chrome extension that will loop through some specific URLs in one tab.我正在尝试构建一个 chrome 扩展,它将在一个选项卡中循环遍历某些特定的 URL。 I am using chrome local storage to store the URLs.我正在使用 chrome 本地存储来存储 URL。 Here is the background.js part where I'm trying to do the tab update,这是我尝试更新标签的background.js部分,

chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
  if (request.message === 'sending_links_of_posts') {
    changeUrl(request);
  }
});

function changeUrl(request) {
  const urlArr = request.url;
  console.log(urlArr);
  chrome.storage.local.set({ urls: urlArr }, function () {
    console.log('Urls stored. \n' + urlArr);
  });
  chrome.storage.local.get(['urls'], function (result) {
    for (let i = 1; i < result.urls.length; i++) {
      console.log('Value currently is ' + result.urls[i]);
      chrome.tabs.update(undefined, {
        url: 'https://m.facebook.com' + urlArr[i],
      });
    }
  });
}

Chrome only opens the first link tab it gets. Chrome 只会打开它获得的第一个链接选项卡。 I've tabs and storage permission in my manifest.json .我的manifest.json中有tabsstorage权限。 I've tried chrome.tabs.create , and that creates new tabs for all the URLs.我试过chrome.tabs.create ,它会为所有 URL 创建新标签。 But I need to update the current tab only.但我只需要更新当前选项卡。 I am using the manifest_version: 2 .我正在使用manifest_version: 2 What am I missing here?我在这里想念什么?

Someone from a discord channel helped me find the answer. discord 频道的某个人帮助我找到了答案。 The function I want to implement can be achieved using this code.我想实现的function可以用这段代码来实现。

let i;

chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
  if (request.message === 'sending_links_of_posts') {
    // initialize index
    i = 0;
    // add urls to local storage
    const urlArr = request.url;
    console.log(urlArr);
    chrome.storage.local.set({ urls: urlArr }, function () {
      console.log('Urls stored. \n' + urlArr);
    });
    // start changing the url
    changeUrl(i);
  }
});

chrome.tabs.onUpdated.addListener((tabId, changeInfo, tab) => {
  // only update after the page has loaded
  if(changeInfo.status === "complete") {
    i++;
    changeUrl(i);
  }
});

function changeUrl(i) {
  chrome.storage.local.get(['urls'], function (result) {
      if (i >= result.urls.length) {
        return;
      }
      console.log('Value currently is ' + result.urls[i]);
      chrome.tabs.update(undefined, {
        url: 'https://m.facebook.com/' + result.urls[i],
      });

  });
}

Wrapping the changeUrl function into a setTimeout or implementing a sleep function can help to slow the URL changing process.changeUrl function 包装到setTimeout或实现sleep function 可以帮助减缓 URL 更改过程。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM