How to organize this code: an extension that launches different code depending on the input data.

I'm building a chrome extension that will need to execute a different js script depending on input data the extension gives it. There will very quickly be 1000's of unique scripts to execute depending on the input.

How would you model this?

I don't think if/else statements are efficient in this case, but I can't store js code in a sqlite db either.

Posted Dec 15, 2018, 6:16 PM UTC · edited

2111
thisisyournamenow•

You should definitely not be storing executed code in a database. You definitely should be using an if/else statement or equivalent to make decisions based on user input.

12
enesimoOP•

I will update the description to add that there will possibly be 1000's of different scripts, so I don't feel like a huge if/else list is a good option.

3
thisisyournamenow•

Okay. So, if I was designing this, I would try and store each script in a separate file. Then, in the database, I would give each file an ID, and a path. Then, someone could select "I want to execute script 5567 whenever I go to google.com". Then my JS would do something like:

  1. listen for url
  2. detect google.com
  3. getScript(google.com) // which would point to 5567 and execute it

​

10
enesimoOP•

This is pretty much what I was looking for and confirms what I was doing already. thanks.

8
Kibouo•

Are they your scripts? Can users add scripts? Are the added scripts available to everyone?

3
enesimoOP•

Yes, users will be able to add scripts. And yes, they will be available to everyone.

1
False1512•

What distinguishes this from greasemonkey or other userscript managers?

2
enesimoOP•

These scripts will have a single purpose, whereas greasemonkey is general purpose.

I have been doing tests on greasemonkey to test my scripts out to make sure they work so they're definitely related.

-2
False1512•

But userscripts can have a single purpose. I just don't see where it's necessary to reinvent the wheel.

3
ex_nihilo•

In Javascript, I would make users write their code inside a function with context provided from your script. Then provide that user function as a callback to the relevant function in the calling script that will setup context.

1
mcg42ray•

They way I would do it:
Define lookup object that has your scripts. The key is your input, processed to make it workable if needed. The value is your script, function, file name, whatever. Take the input, do any needed processing, find the value, execute it.

A long list of if/then is slow, wordy, hard to read, and bug prone. A constant table definition is much more manageable and much faster.

You can even set up the table values so that you can define simple functions inline or have external scripts defined by name and select the appropriate action based o value type.

1