JavaScript Element beforescriptexecute Event

Beginner
⏱️ 11 min read
📚 Updated: Jul 2026
🎯 5 Examples
🚀 5 Try-it labs
Deprecated
Non-standard
Instance event

What You’ll Learn

The beforescriptexecute event once fired before a script ran in Firefox. Cancelling it could stop execution. Learn why it is deprecated and non-standard, how to feature-detect it, how it differed from afterscriptexecute, and which portable approaches to use instead—with five examples and try-it labs.

01

Kind

Instance event

02

Type

Event

03

Cancelable

Yes (legacy)

04

Status

Deprecated · Non-standard

05

Engine

Legacy Gecko only

06

Modern path

CSP / safe loading

Introduction

Early Gecko experiments added a pair of proprietary events around script execution: beforescriptexecute (before run) and afterscriptexecute (after run). The “before” event was interesting because cancelling it could block the script.

That idea never became a web standard. Other browsers never shipped it, MDN warns not to rely on it, and modern Firefox stopped exposing useful web-facing support.

⚠️
Deprecated & non-standard

Learn this event for legacy Firefox code and interviews. For new apps, control scripts with CSP, trusted sources, modules, and careful DOM insertion—not Gecko-only events.

Understanding beforescriptexecute

An instance event on Element (listened on document or other nodes in supporting Gecko). It notified you that a script was about to execute.

  • Fires when a script is about to be executed (legacy Firefox).
  • CancelablepreventDefault() could stop execution.
  • Generic Event — no special payload properties.
  • Siblingafterscriptexecute ran later and was not cancelable.
  • Status — Deprecated and Non-standard on MDN; not part of any specification.

📝 Syntax

Use the event name with addEventListener, or set the handler property (legacy Firefox only):

JavaScript
addEventListener("beforescriptexecute", (event) => { });

onbeforescriptexecute = (event) => { };

Event type

A generic Event.

Cancelable

MDN: cancelling the event prevents the script from executing (in engines that still supported this behavior). Call event.preventDefault() inside the handler.

⚖️ beforescriptexecute vs afterscriptexecute vs CSP

APIWhen it firesPortable?
beforescriptexecuteScript about to run (could cancel)No — legacy Gecko only
afterscriptexecuteScript just finished runningNo — legacy Gecko only
Content Security PolicyBrowser enforces which scripts may runYes — prefer this
script load / errorExternal script finished or failedYes — after-run hooks

🚀 What to Use Instead

There is no portable DOM event that cancels arbitrary scripts the way legacy beforescriptexecute did. Use layered, standard approaches:

  • CSP — declare which script sources (and inline policies) are allowed.
  • Do not inject untrusted scripts — fix the source, not the symptom.
  • ES modules — explicit imports instead of ad-hoc script tags.
  • MutationObserver — some legacy blockers changed a new script’s type before it ran (fragile; CSP is better).
JavaScript
// Educational pattern only — prefer CSP in real apps.
const observer = new MutationObserver((mutations) => {
  for (const mutation of mutations) {
    for (const node of mutation.addedNodes) {
      if (node.nodeName === "SCRIPT") {
        node.type = "text/plain"; // stops it from executing as JS
        console.log("Neutralized an injected script (demo)");
      }
    }
  }
});

observer.observe(document.documentElement, { childList: true, subtree: true });

⚡ Quick Reference

GoalCode / note
Listen (legacy)document.addEventListener("beforescriptexecute", fn)
Handler propertydocument.onbeforescriptexecute = fn
Cancel script (legacy)event.preventDefault()
Event typeGeneric Event
Feature-detect"onbeforescriptexecute" in document (weak; still prefer alternatives)
Modern replaceCSP + safe script loading (not a single event)
MDN statusDeprecated · Non-standard

🔍 At a Glance

Four facts to remember about beforescriptexecute.

Event type
Event

Generic

Cancelable
yes

Legacy Gecko

Standard?
no

Non-standard

New code?
avoid

Use CSP

Examples Gallery

Examples follow MDN Element: beforescriptexecute event and show safe feature detection plus modern replacements. In most current browsers the proprietary event will never fire—the labs still teach the patterns clearly.

📚 Getting Started

Register handlers the MDN ways (legacy Gecko).

Example 1 — addEventListener("beforescriptexecute")

MDN style: listen on document and log when a script is about to run (where supported).

JavaScript
document.addEventListener("beforescriptexecute", (event) => {
  console.log("beforescriptexecute fired");
  console.log("target:", event.target && event.target.nodeName);
});

// In legacy Firefox, inserting/running a <script> could fire this.
// In modern browsers it typically never fires.
Try It Yourself

How It Works

You register the same way as any other DOM event. Support is the hard part: without legacy Gecko behavior, the handler sits idle.

Example 2 — onbeforescriptexecute Property

MDN’s alternate style using the event handler property.

JavaScript
document.onbeforescriptexecute = (event) => {
  console.log("Script about to run (onbeforescriptexecute)");
};

// Assigning again replaces the previous handler.
// Prefer addEventListener when you need multiple listeners.
Try It Yourself

How It Works

Same event, different registration API. One property means one handler—easy to overwrite by accident.

📈 Cancel, Detect & Replace

Show the legacy cancel path, feature-detect safely, and migrate.

Example 3 — Cancel with preventDefault()

MDN: cancelling the event prevented the script from executing (legacy Gecko).

JavaScript
document.addEventListener("beforescriptexecute", (event) => {
  console.log("Blocking script execution (legacy only)");
  event.preventDefault();
});

// Historical Gecko: script does not run after preventDefault().
// Modern browsers: this listener usually never fires.
Try It Yourself

How It Works

This is the main difference from afterscriptexecute: the “before” event could veto execution. That power was never standardized across browsers.

Example 4 — Feature Detection

Never assume the event exists. Check before you depend on it.

JavaScript
const supported = "onbeforescriptexecute" in document;

console.log("onbeforescriptexecute in document:", supported);

if (supported) {
  document.addEventListener("beforescriptexecute", () => {
    console.log("Legacy path: beforescriptexecute");
  });
} else {
  console.log("Use CSP / safe script loading instead");
}
Try It Yourself

How It Works

Presence of the handler property is a rough signal. Even when the property exists, modern engines may not dispatch the event—so still prefer portable controls.

Example 5 — Portable Demo with MutationObserver

Educational stand-in: neutralize an injected script by changing its type.

JavaScript
const observer = new MutationObserver((mutations) => {
  for (const mutation of mutations) {
    for (const node of mutation.addedNodes) {
      if (node.nodeName === "SCRIPT" && node.dataset.demo === "block") {
        node.type = "text/plain";
        console.log("Neutralized demo script");
      }
    }
  }
});

observer.observe(document.documentElement, { childList: true, subtree: true });

const s = document.createElement("script");
s.dataset.demo = "block";
s.textContent = "window.__shouldStayUndefined = true;";
document.body.appendChild(s);

console.log(
  "__shouldStayUndefined:",
  typeof window.__shouldStayUndefined
);
// Prefer CSP in production; this is a teaching demo only.
Try It Yourself

How It Works

Changing type away from JavaScript stops execution for that inserted node. Real apps should still rely on CSP and trusted script sources rather than racing the DOM.

🚀 Common Use Cases

  • Understanding legacy Firefox / Gecko code that tried to block scripts.
  • Migrating old extensions or pages off proprietary script-execute events.
  • Interview / history knowledge of early HTML script lifecycle proposals.
  • Teaching why feature detection and standards matter for DOM events.
  • Choosing CSP and safe loading strategies for real production work.

🔧 How It Works

1

Script is about to run

Browser prepares to execute a <script> element.

Prepare
2

beforescriptexecute (legacy)

Old Gecko dispatched a cancelable Event.

Gate
3

Run or skip

If not canceled, the script executes; then afterscriptexecute could fire.

Decide
4

Prefer CSP today

Control scripts with standards, not proprietary cancel events.

📝 Notes

  • MDN: Deprecated and Non-standard — avoid in production.
  • Cancelable in legacy Gecko; sibling afterscriptexecute was not.
  • Proprietary to Gecko; never a cross-browser API.
  • Modern Firefox stopped shipping useful web-facing support for these events.
  • Related learning: afterscriptexecute, beforexrselect, addEventListener(), JavaScript hub.

Very Limited / Legacy Browser Support

beforescriptexecute is a deprecated, non-standard Gecko event. Logos use the shared browser-image-sprite.png sprite from this project. Other engines never implemented it; modern Firefox no longer dispatches it to web content. Prefer CSP and safe script loading.

Deprecated · Non-standard

Element beforescriptexecute

Do not build features on this event. Use it only to understand or migrate legacy Firefox code.

Legacy Not for new apps
Google Chrome Never implemented
Unavailable
Mozilla Firefox Legacy only · removed / disabled in modern versions
Avoid
Apple Safari Never implemented
Unavailable
Microsoft Edge Never implemented (Chromium)
Unavailable
Opera Never implemented (Chromium)
Unavailable
Internet Explorer No beforescriptexecute support
Unavailable
beforescriptexecute Deprecated

Bottom line: Feature-detect if you must touch legacy Gecko code. For new work, use CSP, modules, and trusted script sources.

Conclusion

beforescriptexecute once let Firefox pages cancel a script before it ran. Today it is a deprecated, non-standard footnote: useful for reading old code, not for shipping new products.

Continue with beforexrselect, afterscriptexecute, or the JavaScript hub.

💡 Best Practices

✅ Do

  • Prefer CSP for controlling which scripts may run
  • Load only trusted scripts from known sources
  • Use ES modules when dependency order matters
  • Feature-detect before touching legacy Gecko-only APIs
  • Plan migration off proprietary script-execute events

❌ Don’t

  • Build new features on beforescriptexecute
  • Assume Chrome, Safari, or Edge ever supported it
  • Confuse cancelable before with non-cancelable after
  • Treat MutationObserver demos as a full CSP replacement
  • Treat non-standard Gecko events as future-proof

Key Takeaways

Knowledge Unlocked

Five things to remember about beforescriptexecute

Legacy Gecko “script about to run” gate — prefer CSP and safe loading now.

5
Core concepts
⚠️ 02

Deprecated

avoid new use

Status
🚫 03

Non-standard

Gecko only

Compat
🛑 04

Was cancelable

preventDefault

API
🚀 05

Replace

CSP / safe load

Modern

❓ Frequently Asked Questions

It is a proprietary Gecko (Firefox) DOM event that fired when a script was about to execute. Cancelling it prevented the script from running. MDN marks it Deprecated and Non-standard. It was never a finished web standard.
No. Prefer Content Security Policy (CSP), avoid injecting untrusted scripts, ES modules with known imports, or MutationObserver-based hardening. Do not rely on this Gecko-only cancel hook.
Yes, in legacy Gecko. MDN states cancelling the event prevented the script from executing. Its sibling afterscriptexecute was not cancelable — it only notified after the script had already run.
Historically only Firefox (Gecko). Other major browsers never shipped it. Modern Firefox stopped dispatching it to web content and later removed the implementation.
In supporting legacy Firefox: document.addEventListener("beforescriptexecute", handler) or document.onbeforescriptexecute = handler. Always feature-detect; do not assume the event exists.
A generic Event. There is no special payload beyond a normal Event object.
Did you know?

Mozilla later unshipped beforescriptexecute and afterscriptexecute from web content because they were non-standard and unused by other browsers. Script blockers that once relied on them moved to portable techniques such as changing a script’s type via MutationObserver—and, better yet, Content Security Policy.

Next: beforexrselect

Learn the experimental WebXR event that protects DOM overlay UI from XR select.

beforexrselect →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

5 people found this page helpful