javascriptgoogle-chrome-extensionember.jsfirefox-addon-webextensions

Accessing Ember.js services from browser extension in versions ≥4.0


In Ember 4.0 and up, access to the Ember global object is deprecated. We have a browser plugin for internal debugging/support purposes that would gather some variables from an ember service using this global object and generate a text report that first-line support personel could use when investigating an issue.

Below is a part of the report generator script for Ember 3.28. This will normally be injected by the extension using chrome.scripting.executeScript with world 'MAIN', but pasting in the console will have the same effect for reproduction purposes. In Ember 4.0 and up, this will throw a TypeError since window.Ember is undefined.

var namespace = window.Ember.Namespace.NAMESPACES.find(ns => ns.name === 'acmecorp');
var sessionService = namespace.__container__.lookup('service:session');
var applicationAdapter = namespace.__container__.lookup('adapter:application');
var user = sessionService.get('user');
var userId = sessionService.get('user.id');
var userType = sessionService.get('user.type');
var userTypePath = applicationAdapter.pathForType(userType ?? 'user');

Following our upgrade to Ember 4.0 and up, is there any way to access this information from a browser extension?


Solution

  • I found a temporary answer in the Ember Inspector init script:

    const Ember = requireModule('ember')['default'];
    

    If you need to be backwards compatible, you can wrap it in a try/catch block like Ember Inspector does

    let Ember;
    
    try {
      Ember = requireModule('ember')['default'];
    } catch {
      Ember = window.Ember;
    }
    

    Note that this only applies to Ember environment that expose requireModule to the global scope via the window object, for other applications/frameworks this does not apply. Also, as NullVoxPopuli notes below, this will break in the future so a better solution, if you are able to change the source, is to expose the relevant service or variables to window yourself.