HOW-TO: run code snippets

Why?

I believe this is will be unnecessary when official Plugin API will come out. But people continue to ask so I’ll put a HOW-TO here.

:warning: Warning :warning:

Running scripts could contain experimental features which can do something with your notes/vault/Obsidian. Be careful and make backups.

How to?

For example, we have this code snippet:

alert("You just run a script")
  1. Open Obsidian.
  2. Press Ctrl+Shift+I/Cmd+Shift+I. This will open developer’s window.
  3. Open Console tab
  4. Paste the code snippet and run enter
  5. You should see a popup which tells us what we just executed a script.
5 Likes

hi, thank you for your work!

Is it possible to autorun some snippets when app starts?

Not in this case. There is an unofficial plugin loader but snippets are not adapted for it.
I believe what soon we will have an official plugin API Beta which will resolve this problem

1 Like

Thanks for the how-to!

For me the shortcut to open the dev tools on mac is I.

I’d like to run code in a .js file that would make an (selected by ID) draggable with the following code, in this case I’m trying to turn the settings into a draggable window. Is there any way to do this?

This is what I’m trying to use:

dragElement(document.getElementByID("modal.mod-settings"));

function dragElement(elmnt) {
  var pos1 = 0, pos2 = 0, pos3 = 0, pos4 = 0;
  if (document.getElementById(elmnt.id + "header")) {
    // if present, the header is where you move the DIV from:
    document.getElementById(elmnt.id + "header").onmousedown = dragMouseDown;
  } else {
    // otherwise, move the DIV from anywhere inside the DIV:
    elmnt.onmousedown = dragMouseDown;
  }

  function dragMouseDown(e) {
    e = e || window.event;
    e.preventDefault();
    // get the mouse cursor position at startup:
    pos3 = e.clientX;
    pos4 = e.clientY;
    document.onmouseup = closeDragElement;
    // call a function whenever the cursor moves:
    document.onmousemove = elementDrag;
  }

  function elementDrag(e) {
    e = e || window.event;
    e.preventDefault();
    // calculate the new cursor position:
    pos1 = pos3 - e.clientX;
    pos2 = pos4 - e.clientY;
    pos3 = e.clientX;
    pos4 = e.clientY;
    // set the element's new position:
    elmnt.style.top = (elmnt.offsetTop - pos2) + "px";
    elmnt.style.left = (elmnt.offsetLeft - pos1) + "px";
  }

  function closeDragElement() {
    // stop moving when mouse button is released:
    document.onmouseup = null;
    document.onmousemove = null;
  }
}
1 Like