如何检查选项卡加载失败

how to check tab load failed

本文关键字:选项 加载 失败 检查 何检查      更新时间:2023-09-26

我需要在更新的选项卡上做一些事情,例如检查页面加载是否正确,并替换页面内的某些内容。 这是我的代码

// background.js
chrome.tabs.onUpdate.addListener(function(tabId, changeInfo, tab){
    try{
       chrome.tabs.executeScript(tabId, filename);
    } catch(e) {
       // 1. when I open a new tab
       // 1. Error during tabs.executeScript: Unknown error.
       // 2. when I request a url not arrive-able.
       // 2. Error during tabs.executeScript: Cannot access contents of url 
       //    "data:text/html,chromewebdata". Extension manifest must request 
       //    permission to access this host.
       // but I can't catch these errors, they just appers in background console.  
    }
});

我尝试在上传时执行脚本,但如果当前选项卡是 chrome://newtab 或 chrome 错误页面,我无法执行此操作,但我无法捕获错误。

没有直接的方法可以捕获这些错误。但是,我刚刚创建了一个实现目标的方法:

  • 使用chrome.tabs.onUpdated(带d
    此事件在页面初始化时触发两次("loading"),当DOM已加载("complete")。
  • 使用chrome.tabs.executeScript(tabId, {file: fileName}, fn_callback);
    第二个参数必须是一个对象,包含 "file""code" 。第三个参数(函数)始终在完成脚本注入后执行。

    现在,真正的实现:
    1. 执行内容脚本(使用 chrome.tabs.executeScript )。
    2. 在注入的内容脚本中,定义onMessage事件。
    3. chrome.tabs.executeScript 的回调函数中,按照以下步骤操作:
    4. 使用 var exec_error = setTimeout(onError, 100); 延迟执行 onError 方法。选择适当的小延迟 (100),并在变量 exec_error 中保存对此超时的引用。
    5. 使用chrome.tabs.sendMessage(tabId, func)向选项卡发送消息。
    6. 在回调函数func 中,添加以下逻辑:
      • 验证响应(事件不是由扩展的另一部分创建的吗?
      • clearTimeout(exec_error)
      • onSuccess()
    7. 发生错误时,不会注入 2. 中定义的onMessage事件。因此,选项卡不会按预期响应,并且不会清除超时。结果,onError将被执行
      否则,将清除超时并执行onSuccess

代码(例如后台脚本):

chrome.tabs.onUpdated.addListener(function(tabId, changeInfo, tab) {
    // This event fires twice: loading, and complete.
    // If we're loading, terminate function, and wait for "complete"
    if (changeInfo.status === 'loading') return;
    // On error and on success, this happens:
    function onError() {
        console.log('Error injecting the content script!');
    }
    function onSuccess() {
        console.log('Successfully injected content script!');
    }
    // Execute scripts
    chrome.tabs.executeScript(tabId, {
        file: 'test_access.js'
    }, function() {
        // This function always fires *after* the attempt to run the code
        var exec_error = setTimeout(onError, 100);
        chrome.tabs.sendMessage(tabId, 'Are you there?', function(yes_no) {
            if (yes_no === 'Yes') {
                clearTimeout(exec_error);
                onSuccess();
            }
        });
    });
});

test_access.js

chrome.extension.onMessage.addListener(function(req, sender, respond) {
   if (req === 'Are you there?') {
       respond('Yes');
   }
});
// Rest of your content script's logic, eg:
alert(location.href);

您无法通过扩展程序加载具有类似 chrome:// 的 url 的页面的脚本。但是,您可以完全覆盖某些页面,但不能在将脚本加载到其他页面的同一扩展名中。