Git Product home page Git Product logo

dotjs-addon's Introduction

dotjs

This is a Firefox Add-on port of defunkt's Chrome extension https://github.com/defunkt/dotjs.

dotjs is a Firefox Add-on that executes JavaScript and CoffeeScript files in ~/.js based on their filename and the domain of the site you are visiting.

If you navigate to http://www.google.com/, dotjs will execute ~/.js/google.com.js and/or ~/.js/google.com.coffee. If you have a ~/.js/default.js, it will execute on every page you visit. Also, you can put site specific .css files in ~/.css (C:\Users\<username>\css\. in Windows 7). default.css loads in all sites.

This makes it super easy to spruce up your favorite pages using JavaScript and CSS.

Bonus: files in ~/.js have jQuery 1.12.4 loaded, regardless of whether the site you're hacking uses jQuery.

GreaseMonkey user scripts are great, but you need to publish them somewhere and re-publish after making modifications. With dotjs, just add or edit files in ~/.js.

Example

$ cat ~/.js/github.com.js
// swap github logo with trollface
$('#header .site-logo img')
.css('width', '100px')
.css('margin-top', '-15px')
.attr('src', 'https://img.skitch.com/20110207-x4s8eys3uy641yk72jigt38bby.png');

How to target a specific path

Sometimes, you don’t want to target a whole domain, but only a path.

CSS

You can use the @-moz-document Mozilla Extension:

/* Full path */
@-moz-document url-prefix(http://www.w3.org/Style/) {
    /* CSS here */
}

/* Regex */
@-moz-document regexp("^https?:\/\/www\.w3\.org\/Style\/.*") {
    /* CSS here */
}

Documentation: https://developer.mozilla.org/en/CSS/@-moz-document

JavaScript

You can test the window.location object:

// Search for a string
if (window.location.pathname.indexOf('/Style/') === 0) {
    // JS here
}

// Regex
if (/^\/Style\/.*/.test(window.location.pathname)) === 0) {
    // JS here
}

Documentation: https://developer.mozilla.org/en/DOM/window.location

Installation

Dependencies

Contributors (Thank you!)

Changelog

v1.13 Fix for subdomains (Issue #43).

v1.12 Now scripts run in private browser windows (Issue #35). Fix issue where scripts were loaded multiple times. Now using jpm.

v1.11 This version now looks up the files recursively for the domains. So for example, for "www.example.com" it will attempt to load: www.example.com.js example.com.js com.js

v1.10 Fixed bug with default.js (Issue #28)

v1.9 Performance optimization. Load content scripts on DOM ready.

v1.8 Updated jquery to v1.9 and coffeescript to v1.4.

v1.7 Updated to version 1.7 of addon sdk along with some optimizations.

v1.6: Leaner, meaner dotjs. A bunch of optimizations by canuckistani (Thanks! \o/).

v1.3: Only load into into the main tab document (vs iframes, etc.).Improves memory usage and performance.

v1.2: Updated to jQuery 1.7.1 and some cleanup (Thanks djl!).

v0.9: CSS support!

v0.8: Windows support! Put your scripts in a js folder under your home directory (C:\Users\<username>\js\. in Windows 7).

v0.7: CoffeeScript support! ~/.js/example.com.coffee gets transpiled to JavaScript and executed.

Credits

"I almost wish you could just stick JavaScript in ~/.js. Do you know what I'm saying?"

dotjs-addon's People

Contributors

bpierre avatar djl avatar eridal avatar evanhahn avatar punassuming avatar rlr avatar tdolsen avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

dotjs-addon's Issues

.dotjs is active!

Hi all,

I'm asking this as a a happy user of this addon.

It's been a while since last updated.

What are the plans for the future?

Pegs CPU in Firefox 6.0

When I have this addon enabled Firefox consistently pegs one of my two cores. If you can't reproduce let me know and I can add more information.

Incorrect document element

While jumping between Chrome and Firefox I noticed that some custom JS scripts I run were not working correctly in Firefox.

Turns out the document element isn't actually a real document object. Instead of returning the expected HTMLDocument object, it returns [object XrayWrapper [object HTMLDocument]].

Is there any way to have document refer to the real HTMLDocument object?

Doc suggestion: How to target a path

Sometimes, you don’t want to target a whole domain, but only a path.

You could add this to the documentation:

How to target a specific path

CSS

You can use the @-moz-document Mozilla Extension:

/* Full path */
@-moz-document url-prefix(http://www.w3.org/Style/) {
  /* CSS here */
}

/* Regex */
@-moz-document regexp("^https?:\/\/www\.w3\.org\/Style\/.*") {
  /* CSS here */
}

Documentation: https://developer.mozilla.org/en/CSS/@-moz-document

JavaScript

You can test the window.location object:

// Search for a string
if (window.location.pathname.indexOf('/Style/') === 0) {
 // JS here
}

// Regex
if (/^\/Style\/.*/.test(window.location.pathname)) {
 // JS here
}

Documentation: https://developer.mozilla.org/en/DOM/window.location

CSS isn't loaded if JS errors

I noticed this interesting case that is possibly unintended.
If you have JS and CSS for a particular domain, and when loading the JS, it errors, the CSS will never be loaded.

This happens because when the eval fails, the entire load-scripts function bails. We could fix this with a try/catch like this:

diff --git i/data/dotjs.js w/data/dotjs.js
index 97aff6e..ec171ee 100644
--- i/data/dotjs.js
+++ w/data/dotjs.js
@@ -13,7 +13,11 @@
         }

         msg.js.forEach(function(script) {
-            eval(script);
+            try {
+                eval(script);
+            } catch(error) {
+                // Maybe log the error?
+            }
         });

         if (msg.coffee) {

For the JS, and coffee phases. I'm happy to submit a PR for this if it's something you think we should handle. Thanks!

window.onload

Chrome's version (at least the port to Windows) runs well before the window load event fires. This, as with all pageMods from the Add-on SDK, runs after.

(NB: I prefer after, since I can just manage the DOM as it already exists, but, meh.)

It's worth considering finding a way to make these compatible. The issue I ran into is that for Chrome, I need to add an onload handler, and for Firefox, load has already fired before this runs, so adding a handler doesn't work.

If I'm the only one to hit this, it's probably the chrome dotjs Windows port's fault.

Firefox 34.0.5

Hi, I upgraded to new version of FF (to 34.0.5) and dotjs not working. Could you please help me?

THX

Crashes Firefox 10.0

I am seeing a consistent crash of FF 10 when closing FF, doing stuff on the addon page and other actions too.

Sample code in readme does not work

The sample should be replaced with working code.

However, I couldn't even get a simple script to run:

$('.header-logo-invertocat').innerHTML("<p>HEADER</p>");

Results in this:

Content Security Policy: The page's settings blocked the loading of a resource at self ("script-src https://assets-cdn.github.com").

[idea] how to require files from within scripts

Allow to require files

This is an idea to allow requirejs' style to include files from the scripts. Currently we only have the default.js and it's getting cluttered for me, so thought about how to make this feature possible.

Interaction

The basic idea is that main.js will inject bridge.js, which will expose the require function to the browser in order to communicate with the nodejs environment.

The main.js will match the files and include them. When these call require, the bridge will emit an event, main.js will require the files and emit the results back to the bridge, which will notify the scripts.

  ┌────────┐      ┌─────────┐                 ┌───────────┐                  ┌────────────────┐
  │ nodejs │      │ main.js │                 │ bridge.js │                  │ example.com.js │
  └────────┘      └─────────┘                 └───────────┘                  └────────────────┘
      │                 │                             │                                │
      │                 ╞════ injects ═══════════════>╞═══╗ declares require shim      │
      │                 │                             │<══╝                            │
      │                 │                             │                                │
      │                 ╞═════ matchFile ═════════════════════════════════════════════>│
      │                 │                             │                                │
      │                 │                             │       require(files, fn)       │
      │                 │               emit(req) ╔═══╡<═══════════════════════════════╡
      │                 │                         ╚══>│                                │
      │                 │                             │                                │
      │                 │<-- on('req') ---------------│                                │
      │ require(files)  │                             │                                │
    ╔═╡<════════════════╡                             │                                │
    ╚═╪════════════════>│ emit(res)                   │                                │
      │                 │                             │                                │
      │                 │--------------- on('res') -->│                                │
      │                 │                             │                                │
      │                 │                             ╞═════════════ fn(err, result) ═>│

      legend:
        --> sync
        ══> async 

Implementation

Please note that this is more like a draft of the idea, than an actual implementation. I have not run the code and it may contain subtle bugs :)

1. main.js

Here we are at nodejs.

We need to add the listener for the bridge, in which we will require the files and send the back. Other than that, the file wont need any other modification.

worker.port.on('.js:require-req', function (req) {
  try {
    worker.port.emit('.js:require-ret', {
      id: req.id,
      result: deps.map(function (dep) {
        return require(dep)
      }),
    })
  } catch (err) {
    worker.port.emit('.js:require-err', {
      id: req.id,
      error : err,
    })
  }
});

worker.port.on('init', function (domain) {
  // 1. inject the 
  worker.port.emit('load-scripts', 'bridge.js');
  // 2. match + emit load-scripts as usual
  // ...
})

2. bridge.js

We are at browser-side, so we declare the window.require shim and declare the hooks required for IPC

var queue = []
var next = 0

window.require = function (deps, done) {

  if (++next === Number.MAX_SAFE_INTEGER) {
    next = 0
  }

  queue[next] = done

  self.port.emit('.js:require-req', { 
    id: next, 
    deps: deps 
  });
}

self.port.on('.js:require-err', function (res) {
  queue[res.id](res.error)
})

self.port.on('.js:require-res', function (res) {
  queue[res.id].call(null, [null].concat(res.result))
})

3. script

This could be an example of a script, that make usage of the require shim.

require([
  'foo',
  'bar/baz',
], function (err, foo, baz) {

  if (err) {
    console.log('boo', err.message)
  }

  console.log('foo', foo)
  console.log('baz', baz)
})

Seems to break JavaScript on some sites

Reddit's JS, though lacking a ~/.js/reddit.com.js file, is busted for one example.

Things like upvotes stopped working. Disabling the extension and refreshing the page gets things working again. Seems to be some sort of clobbering happening?

Support for .html files

I'm currently using dotjs for appending some html+javascript to certain websites but I'm forced to convert the html file to string and append it using a .js file.

Having dotjs do this automatically would be quite useful. Appending small html snippets works ok now but anything above small it's difficult especially html+js+css.

How to debug?

From what I can tell, my code is either never run, or errors out executing. There should be some documentation about how to find error messages when things go wrong.

What's next for .dotjs addon?

With the upcoming changes to Firefox, what's the idea for the extension?

At some point, will it just stop working?

subdomains

I wrote some css for pastebin.mozilla.org and I expected it to always load, but I found on subdomains other than www it doesn't load. I went through the code and see where it excludes www. from the host then looks for an exact match.

I can see why you look for an exact match (subdomains can be completely different sites and you may not wan to apply your js or css) but it seems like this could be a preference (I see you don't have any yet so I understand if that is not the way you want to go).

I propose that it looks for an exact match, then chops off the sub-ist of the subdomains, and looks again until it finds a match.

Hangs & Slow Script Warnings

I noticed lots of mini pauses with Nightly recently and started getting slow script warnings from dotjs. I've disabled and things seem to be better. Today, I only noticed the problem several hours after my last restart, so it could be that it's just leaking or has it's hand in too many tabs...

Since it's a recent development, I'm leaning towards the change from using PageMods, but I don't know the Addon SDK well enough to say that for sure.

Also of note: I have a lot of tabs (142 at the moment, often more, but most aren't loaded), so I may be above the normal threshold.

Sorry I don't have any hard evidence, but it's something to keep an eye out for!

Give the addon a license

First of all I'd like to say thank you for this awesome plugin.

Maybe you and your contributors could GPL the code? As a matter of fact, I don't care too much if you chose the GPL or, say, the X11 License or even public domain.

Without any statement on a license, a cautious hacker could not even fork the code on github, strictly speaking.

Thank you!

update jquery / allow to specify a jquery/framework

jquery should be updated (I recommend moving to 2.x since old browser support is not an issue in Firefox anyway.)

also, there should be a way to specify your own jquery.
an easy solution would be to allow to place a file ~/.js/jquery.js or lets put it more generic ~/.js/framework.js.

of course this raises the question why not just put it into ~/.js/default.js
but I see 2 good reasons:

  • seperate framework from user code
  • just putting my own jquery in default.js would mean double jquery inclusion in dotjs alone

also, it might be a good idea to check with the chrome plugin how they handle this to keep the behavior consistent

Page opened in background tab, some code runs for active tab

I have some code that reworks a site, and it works fine when browsing to a page in the active tab. However, when opening tabs as background tabs (e.g. right click -> Open tab in background tab), the code is not run successfully for that page.

Here's an example:

  • code changes window title with
document.title = document.title.replace("foo", "bar")
  • user opens a link to a background tab
  • title changing code is run for current tab
  • other code specified in the site.js file is run for the background tab

It seems to me that at least some code is run for the background tab. That's why I'm wondering if I'm calling the title changing function in a wrong way.
I think I need some way to access the background tab, but all my other code (jQuery) works without one.

not a bug

This is a great piece of software.
Thank you!

Require paths change with latest FF versions

I just set up dotjs on FF-41 and had to change a bit of the source to allow it to work. i.e. require('file') doesn't work anymore, you need require(/sdk/io/file').

Should I submit the necessary changes as a patch or do we need to keep a separate branch for latest FF sdk?

Specific js code not loaded

Hi

Since several months my specfic JS files aren't loaded. I don't understand why and I've tried a bunch of things but I can't fix that.
I use the last version downloaded from its official page with Firefox 17.0.1.

I tried a simple code to replace all the content of the current page : $('body').html('test');
In the default.js it works fine but it fails if I put it in google.com.js for example :-/

There is no problems with my CSS files.

Does somebody have the same problem or understand what append ?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.