Chrome content scripts in Dart

459 views Asked by At

Is it possible to use dart for chrome extension content scripts? The following does not seem to call anything in main()

import 'dart:html';

import 'package:js/js.dart' as js;

void main() {
  js.context.alert('Hello from Dart via JavaScript');
  window.console.log("START!!!");
  window.alert("alert");
}

manifest.json...

 "content_scripts": [
    {
      "matches": [
        "http://docs.google.com/*",
        "https://docs.google.com/*"
      ],
      "js": [
        "packages/browser/dart.js",
        "packages/browser/interop.js",
        "packages/js/dart_interop.js",
        "out.js"
      ],
      "run_at" : "document_idle",
      "all_frames" : false
    }
  ],
2

There are 2 answers

0
Devon Carew On

I'm not familiar with chrome extension content scripts myself, but from looking at the docs, it seems like they operate in a more restricted world then regular browser scripts. From the docs, they can't:

  • Use chrome.* APIs (except for parts of chrome.extension)
  • Use variables or functions defined by their extension's pages
  • Use variables or functions defined by web pages or by other content scripts

It could be that the dart2js output is running afoul of one of these rules. You can try compiling the dart code with the --disallow-unsafe-eval option. It's used for scripts that need to run in an CSP environment. You might also look in devtools to see if there are any helpful errors -

2
Janez Zemljic On

I did some debugging and I believe there is a bug in dart2js for the chrome.dart.

At the end of the content.dart.js is the code that starts the main function. I added (); to both functions and the main function was called after the change.

Before the change console.log calls from 1-5 were displayed, but not #6. After the change all console.log calls from 1-6 are called and the print() in main function is displayed.

  // BEGIN invoke [main].
  (function(callback) {
    console.log('Begin invoke main 1');
    if (typeof document === "undefined") {
      callback(null);
      return;
    }
    console.log('Begin invoke main 2');
    if (document.currentScript) {
      callback(document.currentScript);
      return;
    }
    console.log('Begin invoke main 3');
    var scripts = document.scripts;
    function onLoad(event) {
      for (var i = 0; i < scripts.length; ++i)
        scripts[i].removeEventListener("load", onLoad, false);
      callback(event.target);
    }
    console.log('Begin invoke main 4');
    for (var i = 0; i < scripts.length; ++i)
      scripts[i].addEventListener("load", onLoad, false);
    console.log('Begin invoke main 5');
  })();    // <-- Added
  (function(currentScript) {
    console.log('Begin invoke main 6');
    init.currentScript = currentScript;
    if (typeof dartMainRunner === "function")
      dartMainRunner(T.main, []);
    else
      T.main([]);
  })();    // <-- Added
  // END invoke [main].