AddonSDK - Is there a way to attach a script from local disk?

Hi,

I hope it’s possible but I couldn’t make it work somehow. I want to attach a script located on disk (for ex: C:\path\to\content_script.js) to the web page using tab.attach() method. Is it possible to run script located other than addon’s directory?

Webextensiosn aren’t allowed access to file system. You can use native messaging, and have the executable read the file and send it to you.

Or you can use hybrid webext, and use bootstrap.js to read from file and send it to your webext.

1 Like

thank you. but I am not developing web extension. I mean “https://developer.mozilla.org/en-US/Add-ons/SDK” by addon sdk. I can connect a sqlite file located on local disk, too. I thought a script file can be opened from local disk. There are Low-Level APIs, but I’m very new at addons and don’t know how to do it.

Something like this should work:

const { Cu, } = require("chrome");
const File = require("sdk/io/file");
Cu.importGlobalProperties([ 'btoa', ]); /* globals btoa, */ const toBase64 = btoa;
// ...
const path = '...'; // not sure if forward / backward slashes matter
if (!File.exists(path)) { throw new Error(`Couldn't find the file "${ path }"`); }
const url = `data:text/javascript;base64,`+ toBase64(File.read(path, encoding)); // encoding is "b" for binary, you'd want text/utf8, don't know what that is

// now attach `url`
1 Like

thank you so much. I’ll try that.

It reads the .js file but can’t convert to appropriate type for tab.attach() method. I tried with encoding=“b” and without encoding. It gives the same error like this.

message:“Unsupported contentScriptFile url: data:text/javascript;base64,LyogV2hpY2ggUHJvZHVjdCBJcyBUaGUgQmVzdCBNYXRjaCAqLwoKdmFyIHF1ZXN0aW9uTmFtZXMgPSBbCgkid2hpY2hfc3VnZ2VzdGlvbl9tYXRjaGVzIgpdOwoKdmFyIGFjY3VyYWN5VXBwZXJMaW1pdCA9IDEwMCwKCWFjY3VyYWN5TG93 VERY LONG RANDOM CHARACTERS HERE ==”

Maybe that’s not possible. contentScriptFile wants resource type uri.scheme as a parameter.

See lines 318-334 from the link.

https://github.com/mozilla/gecko-dev/blob/86897859913403b68829dbf9a154f5a87c4b0638/addon-sdk/source/lib/sdk/content/sandbox.js

I’m sorry. For some reason I was under the impression that you need an URI for tab.attach(). It should work to use the contentScript option as a plain string, without the base64 encoding (which is not random :D):

const File = require("sdk/io/file");
// ...
const path = '...'; // not sure if forward / backward slashes matter
if (!File.exists(path)) { throw new Error(`Couldn't find the file "${ path }"`); }
const file = File.read(path, ''); // encoding, non-binary, i.e. text. Encoding should default to utf8, but you should test it if it matters

// now attach `file`:
tab.attach({ contentScript: file, });
2 Likes