今日已更新 233 条资讯 | 累计 20205 条内容
关于我们

标签:#javascript

找到 546 篇相关文章

AI 资讯

Supercharge your web app with free AI that runs in your users' browser

There is a class of feature that used to be impossible to ship for free: anything that needed a language model. You wired up an API key, you ate the per-token bill, and every prompt your users typed went off to someone else's server. For a small public tool, that math usually killed the idea before it started. That changed. Recent versions of Chrome ship a language model, Gemini Nano, and expose it to any web page through the Prompt API . The model runs on the user's own machine. No API key. No inference bill. No data leaving the browser. We put this into a real, live tool, a free Mermaid diagram editor where you describe a diagram in plain English and the browser writes the Mermaid code for you. This post is the developer's version of that story: how the API actually works, the code that makes a small on-device model trustworthy, and an honest accounting of what you gain and what you give up. What "AI in the browser" means in 2026 The important word is built-in . This is not WebGPU plus a 4 GB model you download and run yourself. The model ships with Chrome, and you talk to it through a small standard-track JavaScript API. As of Chrome 148, the Prompt API is stable for web pages (it had been available to extensions since Chrome 138). It is the general-purpose member of a growing family of built-in APIs: Prompt API ( LanguageModel ): general natural-language prompting, now multimodal (text, plus image and audio input). Summarizer, Writer, Rewriter, Proofreader : task-specific, text-to-text. Translator and Language Detector : backed by expert models, desktop only. The Prompt API is the one you reach for when you need something the task APIs don't cover, like "turn this description into Mermaid source." So that is the one this post focuses on. The 15-line version Here is the whole happy path. Check availability, create a session, prompt it. // Feature-detect first. Old browsers won't have this at all. if ( ' LanguageModel ' in self ) { const status = await LanguageMod

2026-06-21 原文 →
AI 资讯

5 Cookie Tricks for Debugging Auth Issues in Chrome (No More Creating Test Accounts)

Debugging authentication in web apps is painful. You need to test the same flow as five different user types — new visitor, returning user, admin, expired session, logged-out — and the easiest way is to constantly create new accounts or clear all your cookies and start over. There's a faster way. These five techniques use direct cookie manipulation to simulate any auth state without touching your database or creating dummy accounts. I use CookieJar for most of this — a free Chrome extension built natively on MV3 that gives you a proper UI for cookie editing. But I'll show you the underlying Chrome DevTools method too, so you understand what's actually happening. 1. Simulate a Logged-Out State Without Clearing Everything The naive approach: clear all cookies and reload. The problem: you just nuked your dev server session token, your local storage flags, your Stripe test mode cookie, and everything else you carefully set up. The targeted approach : identify and delete only the session/auth cookie. Most session cookies are named session , sid , auth_token , _session_id , or something close. In DevTools: Application → Cookies → [your domain] → find the session cookie → right-click → Delete With CookieJar: open the extension, search session , click the trash icon next to just that cookie. Your dev environment stays intact. The user state resets to logged-out. 2. Test the "Returning User" vs "New User" Path Without a Second Account Session cookies tell the server you're authenticated. But many apps use separate cookies to track whether a user has seen the onboarding flow, completed setup, or visited before. Look for cookies like onboarding_complete , setup_done , first_visit , or custom flags in your app code. To test the new user experience: Export your current cookies (CookieJar → Export → JSON format, or copy from DevTools) Delete the specific onboarding/first-visit flag cookie Reload and test the new user path Re-import or re-set the cookie to restore your state This

2026-06-20 原文 →
AI 资讯

🚀 I Built DG Encoder — A Free Cloudflare Worker API for Storing Secrets, Webhooks, and Dynamic Configurations

As developers, we often need to store webhook URLs, service endpoints, configuration strings, and other values that we don't want exposed directly in frontend code. Most solutions either require setting up a backend, paying for a service, or managing API keys. API URL (Generate your endpoint here): https://dg-encoder.scriptsnsenses.workers.dev/ So I built DG Encoder . A completely free , no-API-key service powered by Cloudflare Workers that lets developers store and retrieve text-based data through simple endpoints. ✨ What is DG Encoder? DG Encoder is a lightweight API that allows you to: Store any text value Receive a unique ID Retrieve the value later through an endpoint Restrict access to specific domains Edit stored entries Delete stored entries Use the service without API keys Use the service completely free 💸 Free Forever One of the main goals of DG Encoder is simplicity. There are: ✅ No API keys ✅ No signup requirements ✅ No subscriptions ✅ No paid plans ✅ No complicated setup Just open the website, encode your value, and start using it. 🔥 Why I Built It While building web applications, I noticed that many developers need a simple way to hide values from frontend code without setting up a full backend system. Common examples include: Discord webhooks Dynamic configuration values Service endpoints Internal URLs Integration strings DG Encoder provides a quick solution by storing those values behind randomly generated IDs. Your application only needs the generated ID instead of the original value. ⚡ Key Features Encode Anything Store any string and receive a unique identifier. { "id" : "abc123xyz" } Domain Restrictions Limit which websites can access a stored value. For example: example.com myapp.pages.dev Only approved domains can successfully use the decode endpoint. Edit Existing Entries Need to replace a webhook or endpoint? Update the stored value without generating a new ID. Delete Entries Remove data whenever it is no longer needed. No API Key Required De

2026-06-20 原文 →
AI 资讯

Conversion Tracking for Developers: From Zero to Full Funnel Visibility

You can't optimize what you don't measure. Every blog post about conversion optimization, A/B testing, or paid ads assumes you have reliable tracking in place. But most developers set up analytics as an afterthought — dropping a script on the page and calling it done. The result is data that's incomplete, untrustworthy, and ultimately useless for making decisions. This guide gives you a developer-first approach to conversion tracking. We'll cover event instrumentation, attribution setup, funnel visualization, and the specific tracking architecture you need to answer real business questions. No marketing jargon. No vague advice. Just the exact setup that turns your analytics from a vanity dashboard into a decision-making tool. The Tracking Mindset Before you write any code, understand what you're trying to learn. Tracking every possible event creates noise. Tracking the wrong events leads to wrong conclusions. Start with one question: "What are the 3-5 actions a user takes between discovering my product and paying me money?" Map these actions in order. That's your funnel. Every event you track should map directly to a step in that funnel. For a typical SaaS product, the funnel looks like this: Discovery: User visits your site from a traffic source Engagement: User reads content, explores features, or uses a tool Intent: User clicks "Sign Up" or "Start Trial" Conversion: User completes signup and activates Revenue: User upgrades to a paid plan If you track these five steps reliably, you can answer 90% of the marketing questions that matter: Which traffic source brings the most valuable users? Where do users drop off? What's my true cost per acquisition? Event Instrumentation: What to Track and How Events are the atomic unit of conversion tracking. An event is any action a user takes that you want to measure. Let's build your event taxonomy from the ground up. Foundational Events (Track These First) These four events are non-negotiable. Set them up before you do anythi

2026-06-20 原文 →
开发者

Toggle navigation not working on ios, android en windows perfect

I need your help. I've problems with an Navigation button on ios. On Windows in all browsers it's working good but on an ios device the menu isnt opening. I've tried to run devtools on an ios device to take a look in the console but this stays empty. https://rb.gy/7o5yql This is the url of the website. I've tried to remove the country flag and the logo i thought it was in the way of the button but nothing helps. Who would like to take a look at it?

2026-06-20 原文 →
AI 资讯

Day 48 of Leaning MERN Stack

Hello Dev Community! 👋 It is officially Day 48 of my unbroken full-stack engineering journey! Yesterday, I refactored my modular core patterns into MVC architecture. Today, I linked up a major functional extension inside the /model layer by introducing JavaScript Classes (OOP) to coordinate my local file operations and storage data patterns! Instead of writing loose object definitions, I stepped up my enterprise game by structuring a reusable class footprint that encapsulates data parameters and handles non-blocking file-system persistence asynchronously. 🧠 Key Learnings From Day 48 (OOP Modeling & File Systems) As clearly shown in my development workspace layout within "Screenshot (116).png" , modeling data with dedicated classes shifts your core structural logic from simple scripts into highly scalable engines: 1. The Model Data Blueprinter ( constructor ) I used the standard ES6 class framework inside home.js to structure an explicit data mold ( houseList ) with attributes tracking: houseName , price , location , rating , and photoUrl . This ensures every entry traveling through our server follows an identical structure. 2. Streamlining Async Persistence ( save() ) Rather than relying on globally declared floating arrays, my .save() blueprint method triggers an internal lookup to read existing data stacks asynchronously before safely using fs.writeFile() to serialize and flash mutated JSON rows into a local data asset ( homesdata.json ). 3. Static Decoupled Fetchers ( static fetchAll() ) I mastered using static methods. Since reading a data grid requires pulling records without creating an instance of a single house first, making fetchAll(callback) static allows our controllers to tap the hard disk records straight from the class reference layout: javascript // A conceptual look at my file-reading design today static fetchAll(callback) { const filePath = path.join(rootDir, 'data', 'homesdata.json'); fs.readFile(filePath, (err, data) => { if (err) { callback(JSON.

2026-06-20 原文 →
AI 资讯

Passkeys in 2026: A Practical Engineering Guide to Passwordless Auth

Authentication is broken at its foundation - not just inconvenient. Passwords are shared secrets: hand one to a server, and you have instantly doubled your attack surface. With over 5 billion passkeys now active globally and Google reporting a 99.9% lower account compromise rate compared to passwords, the industry has already moved. This guide covers how passkeys work cryptographically, how to implement them in TypeScript, and the pitfalls to avoid before going to production. Why Passwords Are Structurally Broken The core issue isn't that users pick weak passwords - it's that passwords require a shared secret stored on both sides. The Verizon 2025 DBIR found that 22% of all breaches started with stolen credentials, and 88% of web app attacks relied on them. In 2024, infostealer malware alone harvested 548 million passwords. Adding 2FA helps but doesn't fix the root problem: SMS codes are SIM-swap targets, and TOTP tokens can be phished in real time by proxy attackers who replay codes within their validity window. What Passkeys Actually Are A passkey is a credential built on public-key cryptography, standardized through the WebAuthn spec and FIDO2. When you register, your device generates a public-private key pair - the private key stays locked in hardware (Secure Enclave, StrongBox, or a hardware key), and the server only receives the public key. At login, the server sends a random challenge, your device signs it with the private key after biometric or PIN verification, and the server verifies the signature. No secret is ever transmitted. This eliminates credential stuffing, server-side breach exposure, and phishing - because passkeys are cryptographically bound to a specific origin domain. The Cryptography Worth Understanding The standard algorithm is ES256 - ECDSA with the P-256 curve and SHA-256. Each credential is tied to a specific relying party ID (your app's domain). A passkey created for yourapp.com cannot be used on yourapp-phishing.com because the origin i

2026-06-20 原文 →
AI 资讯

UseState in React (A beginner's guide)

Your password bar goes from "weak" to "strong" when you add characters. Have you ever wondered how React 'remembers' your inputs? 'State' is your answer. A state remembers what input you added. Assume you are typing your name "John", initial state is the blank slate (starting value, like empty input, counter at zero, or an empty whiteboard) in the input bar, whenever you add a new letter, a function named 'setState' is called to change the state from "" (empty input bar) to "J", then again to "Jo", again to "Joh", etc... And following the setState, React automatically re-renders the UI. Think of re-rendering as erasing everything and re-writing the UI with the new state. Initial state was "", then setState updates it from "" to "J". Following that, React automatically erases the first UI and then it will build a new UI with the new state. Why not just use a variable? You might be thinking, "Why don't just use variables and change them whenever you want it?", and you might do that, but the value only changes in your codebase, but the UI will still show the first value. (and that defeated the purpose) What is [state, setState] concept? const [state, setState] = useState('placeholder') is the basic syntax. useState provides an array of ['current-state', 'function to change state']. It is destructured to the two values (state = 'current-state' and setState = 'function to change state'). When you enter an input, the function is called and the 'current-state' will be updated to the 'new-state'. How to use it To use useState follow these two simple steps: Import useState from 'react' import { useState } from 'react'; Declare it (for example to input age): const [age, setAge] = useState(20); where, 'age' is current state. 'setAge' is the function that will create the new state. 20 is the placeholder. Now try it yourself! Open your React project and add a counter using useState. Watch the UI update every time you click.

2026-06-20 原文 →
开发者

How to open Google Maps in turn-by-turn navigation mode from a PWA (Android)

The next attempt was the standard Maps URL: window . open ( `https://maps.google.com/maps?daddr= ${ lat } , ${ lng } ` , ' _blank ' ); This opens Maps, but in the browser — not the app. And it shows the route preview, not turn-by-turn navigation. What worked: Android Intent URLs Android supports a special URL scheme that tells Chrome to launch a native app directly: window . location . href = `intent://navigation/now?ll= ${ lat } , ${ lng } &title=Next+stop#Intent;scheme=google.navigation;package=com.google.android.apps.maps;end` ; Breaking it down: intent:// — tells Chrome this is an Android intent navigation/now?ll=${lat},${lng} — opens Maps in navigation mode, starting immediately #Intent;scheme=google.navigation — the URI scheme to use package=com.google.android.apps.maps — the target app package end — closes the intent syntax This opens the Google Maps app directly and starts turn-by-turn navigation automatically — no extra taps needed. It also works with Android Auto. The full function export function openNavigation ( destination : { lat : number ; lng : number }): void { window . location . href = `intent://navigation/now?ll= ${ destination . lat } , ${ destination . lng } &title=Next+stop#Intent;scheme=google.navigation;package=com.google.android.apps.maps;end` ; } Call it on any user gesture (tap, click) and it works without being blocked by the browser. The app The full PWA is open source if you want to see the context: 🔗 GitHub repo 🌐 Live app Built with React + TypeScript + Vite + Dexie.js + @vis .gl/react-google-maps. If you're building a PWA that needs to hand off to Google Maps navigation on Android, this intent URL is the cleanest solution I found. Hope it saves you the hour I spent figuring it out.

2026-06-20 原文 →
AI 资讯

YINI Config Format Specification RC 6 released - clearer strings, stricter parsing, and growing tooling ecosystem

YINI Specification RC 6 is now released The YINI configuration format has reached Specification Release Candidate 6 . YINI is a configuration format designed to feel familiar if you like INI-style files, but designed to bring more explicit structure, clarity, useful data types, and predictable parsing rules to real-world configuration needs.. The short version: @yini ^ App name = "Example" version = "1.0.0" debug = false ^^ Server host = "127.0.0.1" port = 8080 ^^ Features enabled = [ "auth", "logging", "metrics", ] YINI tries to sit somewhere between classic INI, JSON, TOML, and YAML: More structured than traditional INI. Less punctuation-heavy than JSON. Indentation-insensitive unlike YAML. Explicit about parsing rules and validation behavior. RC 6 is an important release because it tightens several parts of the language and moves the format closer to a stable 1.0 specification. What changed in RC 6? RC 6 includes a number of syntax and behavior updates. The main theme is the same as before: Make the format clear for humans, but deterministic for parsers. Here are some of the notable updates. Clearer section markers YINI uses section markers to define structure. ^ App name = "MyApp" ^^ Server host = "localhost" ^^^ TLS enabled = true The number of section markers defines the nesting level. This keeps hierarchy visible without relying on indentation. The primary section marker is: ^ YINI also supports alternative section markers, but ^ remains the recommended default for most files and examples. Strict and lenient mode behavior is more clearly defined YINI has two parsing modes: Lenient mode — practical, forgiving, and intended as the default. Strict mode — validation-focused and intended for stricter tooling, CI checks, and production-sensitive configuration. A file can declare its intended mode: @yini strict or: @yini lenient RC 6 clarifies how these declarations should behave when the file is parsed in a different mode. The goal is to avoid silent surprises. If

2026-06-20 原文 →
AI 资讯

I built a Chrome extension that catches every dark pattern trick on shopping sites. Here's exactly how.

A few months ago I was about to buy a flight. The page showed "Only 2 seats left at this price" in red letters. I hesitated, then refreshed the page out of curiosity. The counter said "Only 2 seats left" again. Same number. It had been resetting on every page load the whole time. That's when I started cataloguing every trick I'd seen on shopping sites and built a Chrome extension that flags them automatically, in real time, on any page. This isn't just my opinion — it's documented research In 2019, Princeton and University of Chicago researchers scraped 11,000 shopping sites and found dark patterns on more than 1,250 of them. The FTC has since fined several companies specifically for fake countdown timers and pre-checked subscription boxes. This isn't a grey area anymore — it's a known, studied, and increasingly regulated practice. The extension targets four categories that account for most of what's out there. The four patterns Fake urgency. Countdown timers that reset, "X people are viewing this" badges that never change, "only N left in stock" that's been static for a week. Trap checkboxes. A checkbox for "Yes, sign me up for the newsletter" that's pre-checked and styled to blend into the page so you don't notice it. Confirmshaming. The decline button reads "No thanks, I don't want to save money" instead of just "No thanks." Psychological pricing. Prices ending in .99 or .95 designed to register as a lower price bracket than they are. Why no AI this time My phishing detector used Claude because language and intent are genuinely ambiguous — you need a model that understands context. Dark patterns are different. They're structural. A countdown timer either resets on reload or it doesn't. A checkbox is either pre-checked or it isn't. That's a DOM query, not a judgment call. So this one runs entirely on regex and DOM inspection. No API calls, no latency, no cost per scan, works offline. Sometimes the boring solution is the correct one. Detecting the urgency pattern T

2026-06-20 原文 →
AI 资讯

Architecting Block: Building a Custom Social Network, Theme Engine, and more

Pre: What is BlockSocial? BlockSocial is the ultimate social network for developers, bringing the energy of short-form video to the world of open source. Think of it as Facebook meets Instagram—a place to showcase your code, find inspiration, and build your developer brand through "Reels" and interactive dashboards. Github link: https://github.com/Hfs2024/BlockSocial 1. User Scenario & Workflow (The Fork System) The Setup User A : Publishes a post saying: "I love drinking Pepsi every day." User B : Is shy, but wants to tell their friend this is an unhealthy habit. User C : Is a malicious user who gossips. The Fork Mechanism User B creates a fork to discuss this post with User C via the POST /api/share endpoint. Data Copying : It copies the entire post contents except comments, likes, reports, and downloads. Chain Prevention : You can fork a forked post, but the system will fork the original source root, not the fork itself. Scope : It shares with only one user at a time to prevent unexpected group creation. Database Payload for Forks The following fields are appended to the document structure: { "share" : true , "shareId" : "post._id" , // The original post ID "sharedBy" : "req.currentUser.username" , // The user who shared or forked "shareTo" : "shareTo" , // The friend receiving the share "shareComment" : "comment || ''" // A quick comment on the post } Moderation & Enforcement Workflow If User C breaks trust and leaks the conversation, User B can report them via the POST /report/user endpoint. Verification : Administrators review interaction history to verify the violation. Account Termination : Bad users receive a permanent lifetime account ban. Data Scrubbing : All associated messages from the malicious user are removed. Blacklisting : The account is fully banned. The Blindspot : Face-to-face interactions remain outside system moderation boundaries 😅 2. Technical Implementation Details Dynamic Comment Identity Logic When a user submits a comment via POST /api/c

2026-06-19 原文 →
AI 资讯

Unit Test AI Guide — Zero Hallucination, Cross-Stack Standard

Focus: Unit Tests ONLY — no integration, no E2E Stacks: Node.js (NestJS/Express) · React.js · Python · Angular · Laravel Goal: AI generates unit tests consistently, deterministically, without hallucination IDE: Cursor (Primary) + Claude (Secondary) Part 1 — Best Single Library Per Stack (Final Decision) Do not mix libraries. Pick one per stack, configure it fully, never deviate. | Stack | Library | Why This One | |---|---|---| | Node.js / NestJS / Express | Jest | Native DI mocking, @nestjs/testing built around it, widest ecosystem | | React.js | Vitest + @testing-library/react | Native Vite/ESM support, Jest-compatible API, 3–10x faster | | Python | pytest | De facto standard, fixture system eliminates boilerplate, best plugin ecosystem | | Angular | Jest (replace Karma) | Karma is deprecated in Angular 17+; Jest is the official migration target | | Laravel | Pest | Modern syntax, built on PHPUnit, higher signal-to-noise ratio | Rule: If someone suggests a second library for the same stack, reject it. One library per stack, configured once, followed always. Part 2 — IDE: Cursor (Only Choice for This Goal) Why Cursor and Not VS Code / WebStorm | Capability | Cursor | VS Code + Copilot | WebStorm | |---|---|---|---| | Project-level AI rules | ✅ .cursor/rules/ | ❌ | ❌ | | Codebase-aware context | ✅ @codebase | Partial | Partial | | Run terminal + read output | ✅ Composer | ❌ | ❌ | | Multi-file generation | ✅ Agent mode | Limited | ❌ | | Custom instructions per filetype | ✅ | ❌ | ❌ | | MCP server integration | ✅ | ❌ | ❌ | Cursor's .cursor/rules/ system is the only IDE-native mechanism that injects persistent, project-scoped instructions into every AI interaction — this is what prevents hallucination at the source. Cursor Setup for This Project project-root/ ├── .cursor/ │ └── rules/ │ ├── unit-test-global.mdc ← applies to all files │ ├── unit-test-nestjs.mdc ← applies to *.service.ts, *.guard.ts │ ├── unit-test-react.mdc ← applies to *.tsx, *.component.tsx │ ├── unit-t

2026-06-19 原文 →
开发者

TSRX: A Framework-Agnostic Alternative to JSX

TSRX is a TypeScript language extension developed by Dominic Gannaway, designed to build declarative user interfaces in a framework-agnostic manner. It compiles single .tsrx files to various runtime targets and supports scoped styles and declarative error handling. TSRX is currently in alpha and is open source under the MIT license. By Daniel Curtis

2026-06-19 原文 →