如何避免错误:无法访问 chrome:// URL

问题描述 投票:0回答:2

我是 chrome 扩展开发的新手,在开发过程中,当我尝试在 chrome 浏览器的起始页上打开我的扩展时,我在控制台中收到此错误。

link for image

未捕获(承诺)错误:无法访问 chrome:// URL

我可以避免这个错误或有其他方法来修复它吗?

我还阻止打开扩展窗口,但这不是问题的解决方案

来自 App.vue 文件的代码

chrome.tabs.query(queryOptions, (tabs) => {
  let url = tabs[0].url;
  if (url.indexOf("chrome://") !== -1) {
    window.close();
  }

背景.js

chrome.action.onClicked.addListener(function(tab) {

    chrome.scripting.executeScript({
        target: {tabId: tab.id},
        files: ['js/inject.js']
    });
    chrome.scripting.insertCSS({
        target: {tabId: tab.id},
        files: ['css/inject.css']
    });

});

我需要保持此窗口不在浏览器的起始页上打开,但我还需要修复此错误的抛出。

javascript vue.js google-chrome-extension chrome-extension-manifest-v3
2个回答
0
投票

解决方案,我从评论作品中得到的,只需将其全部包装起来,只需检查

tab.url

    chrome.action.onClicked.addListener(function(tab) {

    console.log(tab.url);
    if (tab.url.includes('chrome://')){
        console.log('can`t run on start page')
    } else {
        console.log(tab.url);
        chrome.scripting.executeScript({
            target: {tabId: tab.id},
            files: ['js/inject.js']
        });
        chrome.scripting.insertCSS({
            target: {tabId: tab.id},
            files: ['css/inject.css']
        });
    }



0
投票

要防止执行background.js文件中的脚本,您可以使用以下代码:

chrome.tabs.get(tabId, (tab) => {
    // Check if the tab's URL is allowed
    if (tab.url && tab.url.startsWith("http")) {
      // Your codes...
    } else {
      console.error("Cannot execute script on this URL:", tab.url);
    }
});
© www.soinside.com 2019 - 2024. All rights reserved.