Manage App Lifecycle

Like everything in this world, apps have a lifecycle. They are installed, launched, restarted, suspended when the system needs to free up resources and uninstalled. This lab will show you the basics of the Chrome app lifecycle and how its heart, the event page (aka background script), is used.

The event page

The event page is one of the most important pieces of a Chrome app. It's responsible for what gets launched, when, and how. For example, if your app is an instant messenger, you might want your event page to only show a UI when there is a new notification.

For simpler apps, the event page listens to the app lifecycle events and reacts appropriately. There are two important lifecycle events, app.runtime.onLaunched and app.runtime.onRestarted.

The onLaunched event

The app.runtime.onLaunched event is the most important event. It fires when the user clicks on your app's icon with the intent of launching it. For most simpler apps, the event page will listen for this event and open a window when it fires. See AngularJS main.js or JavaScript main.js for the most common usage.

Windows with IDs

The app.window.create method can associate an ID to the window being opened. Currently, the most interesting use for this is to restore a window's width, height and location and its associated Developer Tools window, if opened, when the app is launched.

Execute your app as it is now, move and resize the window, close and restart it. The app will reopen in the original location, right? Now add a property id to the event page, Angular main.js or JavaScript main.js, reload the app and test again:

chrome.app.runtime.onLaunched.addListener(function() {
    chrome.app.window.create('index.html',
      {id: 'mainwindow', bounds: {width: 500, height: 309} });
  });

If your application requires, you can open more than one window.

The onRestarted event

The app.runtime.onRestarted event is not as essential as onLaunched, but it might be relevant to certain types of apps. This event is executed when the app is restarted, for example, when Chrome quits, restarts, and the app is launched again. You can use this event to restore a transient state.

For example, if your app has a form with several fields, you won't always want to save the partial form while the user is typing. If the user quits the app on purpose, she might not be interested keeping the partial data. If the Chrome runtime restarted for some reason other than by a user's intention, the user will want that data when the app is restarted.

Let's change our code to save the Todo input field in storage as the user types, only restoring it if the onRestarted event is triggered.

Note: We learned about chrome.storage.sync before, but chrome.storage.local wasn't mentioned until now. Both have exactly the same syntax, but the semantics of chrome.storage.local is, as the name says, completely local. There's no attempt to synchronize or to save the data in the cloud.

Update event page

Update the event page to include the onLaunched and onRestarted events. Events are handled the same in AngularJS main.js and JavaScript main.js:

chrome.app.runtime.onLaunched.addListener(function() {
  // normal launch initiated by the user, let's start clean.
  // note that this is not related to the persistent state, which is
  // appropriately handled in the window code.
  runApp(false);
});

chrome.app.runtime.onRestarted.addListener(function() {
  // if restarted, try to get the transient saved state
  runApp(true);
});

function runApp(readInitialState) {
  chrome.app.window.create('index.html',
    {id: 'mainwindow', bounds: {width: 500, height: 309} },
    // the create callback gets a reference to the AppWindow obj
    function(win) {
      // when the callback is executed, the DOM is loaded but no script was
      // loaded yet. So, let's attach to the load event.
      win.contentWindow.addEventListener('load', function() {
        if (readInitialState) {
          win.contentWindow.setInitialState();
        } else {
          win.contentWindow.clearInitialState();
        }
      });
    });
}

Update controller

Add to existing AngularJS controller.js or JavaScript controller.js:

Angular
JavaScript
var newTodoInput = null;

var clearInitialState = function() {
  chrome.storage.local.set({'newtodo': null});
}

var setInitialState = function() {
  chrome.storage.local.get('newtodo', function(data) {
    if (newTodoInput && data && data.newtodo) {
      newTodoInput.value = data.newtodo;
      newTodoInput.focus();
    }
  });
}

window.addEventListener('load', function() {
  var saveTransientState = function() {
    chrome.storage.local.set({'newtodo': newTodoInput.value});
  };
  newTodoInput = document.querySelector('input[type="text"]');
  newTodoInput.addEventListener('keypress' , function() {
    saveTransientState();
}) })
  var newTodoInput = document.querySelector('input[type="text"]');
 
  window.clearInitialState = function() {
    chrome.storage.local.set({'newtodo': null});
  }

  window.setInitialState = function() {
    chrome.storage.local.get('newtodo', function(data) {
      if (newTodoInput && data && data.newtodo) {
        newTodoInput.value = data.newtodo;
        newTodoInput.focus();
      }
    });
  };

  var saveTransientState = function() {
    chrome.storage.local.set({'newtodo': newTodoInput.value});
  };

  newTodoInput.addEventListener('keypress' , function() {
    saveTransientState();
  })
    

Check the results

Save the changes by reloading the app: open the app, right-click and select Reload.

If Chrome and the app shuts down for any reason (other than a user-gesture), the onRestarted event is fired. Any text entered in the input field (but not yet saved as a Todo item) will reappear when Chrome and the app are reopened.

If you get stuck and want to see the app in action, go to chrome://extensions, load the unpacked AngularJS app or JavaScript app, and launch the app from a new tab.

Takeaways

  • The event page may continue to run even when your windows are closed; you can move logic that is shared amoung windows to the event page.

You should also read

Manage App Lifecycle tutorial

What's next?

In 6 - Access User's Data, you will learn how to identify users and use OAuth2.0 to access Google and other third party services.

Note: The next chapter covers a still experimental API. If you don't want to play with experimental APIs, feel free to skip it - the rest of the codelab is independent from it.