captain dragon
captain dragon

Reputation: 1409

chrome.tabs.executeScript - succeeded?

How can I know if my execution happened successfully?
I know executeScript offer a callback, but if the script was blocked for some reason, the callback would never happen.

How can I know that?

Upvotes: 0

Views: 1954

Answers (1)

Rob W
Rob W

Reputation: 348992

There are two ways to check whether a chrome.tabs.executeScript call has succeeded:

  1. Check if the results property is an array (it's undefined on failure).
  2. Check if the chrome.runtime.lastError property is set (this is the recommended way).
chrome.tabs.executeScript(tabId, {
    code: '// some code'
}, function(result) {
    if (chrome.runtime.lastError) { // or if (!result)
        // Get the error message via chrome.runtime.lastError.message
        return;
    }
});

The previous example only shows when an error occurred while inserting a content script. It doesn't show any error for runtime errors. If you want to find out whether an error occurred in your script, open the devtools for the tab. If you need to know whether an error occurred from the background page, return a value from the content script to signal that the script has (not) run correctly.
The value of the last expression is passed to the callback of chrome.tabs.executeScript (in an array, because multiple values are passed when allFrames:true is set).

Upvotes: 1

Related Questions