如何检查标签加载失败

gui*_* 桂林 6 javascript google-chrome google-chrome-extension browser-tab

我需要在更新的标签上做一些事情,比如检查页面加载是否正确,并替换页面内的内容.这是我的代码

// 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.  
    }
});
Run Code Online (Sandbox Code Playgroud)

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

Rob*_*b W 11

没有直接的方法来捕捉这些错误.但是,我刚刚创建了一种方法来实现目标:

  • 使用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,添加以下逻辑:
    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();
            }
        });
    });
});
Run Code Online (Sandbox Code Playgroud)

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);
Run Code Online (Sandbox Code Playgroud)


Juz*_*Ali 0

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