More from Dariusz Winkler | Software development
I have recently moved my website to a new domain. My old posts may reappear in your feed reader — sorry for the inconvenience! I redirect the RSS feed to the new domain, but you might want to update the URL in your reader. I've also merged my dev, photography, and personal posts into a single feed. If you're only interested in one of these categories, you can subscribe to the corresponding feed: All posts Software development posts Photography posts Personal posts I'll soon publish an update on my website redesign — stay tuned!
When I copy a browser tab URL, I often want to also keep the title. Sometimes I want to use the link as rich text (e.g., when pasting the link into OneNote or Jira). Sometimes I prefer a Markdown link. There are browser extensions to achieve this task, but I don't want to introduce potential security issues. Instead, I've written a bookmarklet based on this example extension. To use it, drag the following link onto your browser bookmarks bar: Copy Tab When you click the bookmark(let), the current page including its title will be copied into your clipboard. You don't even have to choose the output format: the link is copied both as rich text and plain text (Markdown). This works because it's possible to write multiple values into the clipboard with different content types. Here's the source code: function escapeHTML(str) { return String(str) .replace(/&/g, "&") .replace(/"/g, """) .replace(/'/g, "'") .replace(/</g, "<") .replace(/>/g, ">"); } function copyToClipboard({ url, title }) { function onCopy(event) { document.removeEventListener("copy", onCopy, true); // hide the event from the page to prevent tampering event.stopImmediatePropagation(); event.preventDefault(); const linkAsMarkdown = `[${title}](${url})`; event.clipboardData.setData("text/plain", linkAsMarkdown); const linkAsHtml = `<a href="${escapeHTML(url)}">${title}</a>`; event.clipboardData.setData("text/html", linkAsHtml); } document.addEventListener("copy", onCopy, true); document.execCommand("copy"); } copyToClipboard({ url: window.location.toString(), title: document.title }); Reply via email
I'm a frequent user of bookmarklets. As I'm sharing some of them on my blog, I wrote this post to explain what bookmarklets are and how to use them. In short, a bookmarklet is a browser bookmark containing JavaScript code. Clicking the bookmark executes the script in the context of the current web page, allowing users to perform tasks such as modifying the appearance of a webpage or extracting information. Bookmarklets are a simpler, more lightweight alternative to browser extensions, Chrome snippets, and userscripts. How to add a bookmarklet? Here's an example to display a browser dialog with the title of the current web page: Display page title You can click the link to see what it does. To run this script on other websites, we have to save it as a bookmarklet. My preferred way is to drag the link onto the bookmarks toolbar: A link on a web page is dragged and dropped onto a browser bookmark bar. A bookmark creation dialog appears. The prompt is confirmed and closed. The created bookmarklet is clicked. The current web page title is displayed in a browser dialog. Another way is to right-click the link to open its context menu. In Firefox, you can then select "Bookmark Link…": Other browsers make it a little more difficult: select "Copy Link (Address)", manually create a new bookmark, and then paste the copied URL as the link target. Once created, you can click the bookmark(let) on any web page to display its title. Scroll further down to see more useful use cases. How to write a bookmarklet? Let's start with the code for the previous bookmarklet example: window.alert(document.title) To turn that script into a bookmarklet, we have to put javascript: in front of it: javascript:window.alert(document.title) To keep our code self-contained, we should wrap it with an IIFE (immediately invoked function expression): javascript:(() => { window.alert(document.title) })() Finally, you might have to URL-encode your bookmarklet if you get issues with special characters: javascript:%28%28%29%20%3D%3E%20%7B%0A%20%20window.alert%28document.title%29%0A%7D%29%28%29 Useful bookmarklets Here are some bookmarklets I've created: Copy Tab — copy browser links and titles in one click (as Markdown and rich text). Debugger — Starts the browser DevTools debugger after 3 seconds, useful for debugging dynamic content changes. Log Focus Changes — Logs DOM elements when the focus changes. Design Mode — Makes the web page content-editable (toggle). Reply via email
It can be frustrating to fill out a web form, only to accidentally refresh the page (or click "back") and lose all the hard work. In this blog post, I present a method to retain form data when the page is reloaded, which improves the user experience. Browser behavior Most browsers provide an autofill feature. In the example form below, enter anything into the input field. Then, try out the following: Click the "Example link" and use the "back" functionality of your browser. Reload the page. Query Example link Depending on your browser, the input value might be restored: BrowserReloadBack Firefox 130YesYes Chrome 129NoYes Safari 18NoYes How does it work? I was surprised to learn that this autofill behavior is controlled via the autocomplete, that's mostly used for value autocompletion from past web forms. However, if we disable the autocompletion, the autofill feature will be disabled as well: <input autocomplete="false" /> To learn more about the behavior, read the full spec on persisted history entry state. Preserving application state Even with autofill, no browser will restore dynamic changes previously triggered by the user. In the following example, the user has to always press the "Search" button to view the results: This is an interactive example. Please enable JavaScript to use it. Query Search...const inputElementNative=document.querySelector("#example-search-input"),outputElementNative=document.querySelector("#example-search-output"),performSearch_exampleSearch=e=>{e.innerText="";const t=document.createTextNode("Open the result for ");e.appendChild(t);const n=document.createElement("a");n.href="https://example.com",n.innerText=inputElementNative.value||"no text",e.appendChild(n)};document.querySelector("#example-search-form").addEventListener("submit",e=>{e.preventDefault(),performSearch_exampleSearch(outputElementNative)}) If the web page changes its content after user interaction, it might be a good idea to restore the UI state after the page has been refreshed. For example, it's useful to restore previous search results for an on-site search. Note that Chrome will fire a change event on inputs, but this is considered a bug as the respective spec has been updated. Storing form values As the form value might be lost on reload, we need to store it temporarily. Some common places to store data include local storage, session storage, cookies, query parameters or hash. They all come with drawbacks for our use case, though. Instead, I suggest using the browser history state, which has several advantages: We get data separation between multiple browser tabs with no additional effort. The data is automatically cleaned up when the browser tab is closed. We don't pollute the URL and prevent page reloads. Let's store the search input value as query: document.querySelector("form").addEventListener("submit", (event) => { event.preventDefault(); const inputElement = document.querySelector("input"); history.replaceState({ query: inputElement.value }, ""); performSearch(); }); This example uses the submit event to store the data, which fits our "search" use case. In a regular form, using the input change event might be a better trigger to store form values. Using replaceState over pushState will ensure that no unnecessary history entry is created. The second parameter to "replaceState" isn't used, but it's mandatory. If the argument is left out, the browser will throw an error: Uncaught TypeError: Failed to execute 'replaceState' on 'History': 2 arguments required, but only 1 present. Restoring form values My first approach to restore form values was to listen to the pageshow event. Once it's fired, we can access the page load type from window.performance: window.addEventListener("pageshow", () => { const type = window.performance.getEntriesByType("navigation")[0].type; const query = history.state?.query; if (query && (type === "back_forward" || type === "reload")) { document.querySelector("#my-input").value = query; performSearch(); } }); I'll keep the solution here in case someone needs it, but usually it's unnecessary to check the page load type. Because the history state is only set after the search form has been submitted, we can check the state directly: const query = history.state?.query; if (query) { document.querySelector("#my-input").value = query; performSearch(); } Demo Here's an example combining both techniques to store and restore the input value: This is an interactive example. Please enable JavaScript to use it. Query Search...const inputElementCustom=document.querySelector("#example-preserve-input"),outputElementCustom=document.querySelector("#example-preserve-output"),performSearch_examplePreserve=e=>{e.innerText="";const t=document.createTextNode("Open the result for ");e.appendChild(t);const r=document.createElement("a");r.href="https://example.com",r.innerText=inputElementCustom.value||"no text",e.appendChild(r)};document.querySelector("#example-preserve-form").addEventListener("submit",e=>{e.preventDefault(),performSearch_examplePreserve(outputElementCustom),history.replaceState({query:inputElementCustom.value},"")});const historyQuery=history.state?.query;historyQuery&&(document.querySelector("#example-preserve-input").value=historyQuery,performSearch_examplePreserve(outputElementCustom)) Conclusion Preserving form data on page refresh is a small but impactful way to improve user satisfaction. The default browser autofill feature handles only basic use cases, so ideally we should maintain the form state ourselves. In this blog post, I've explained how to use the browser history state to temporarily store and retrieve form values. Reply via email
More in programming
Helping Scout focus and remember
tl;dr: the Explorer Pattern is one individual or team building a functional implementation that minimizes cross-team and cross-functional impacts as much as humanly possible, and then reconciling the details with other teams after that prototype is completed, accepting that this approach can require very substantial rework to that initial development. Why write this? Imprint previously called this the “Tech-led” or “Engineering-led” development model, but it’s pretty unclear to folks what that means. This writeup provides a more defined term, the “Explorer Pattern”, and explains in more detail how this works. Why do we need to adjust the way we work? Before 2026: Code is expensive, and we design process to minimize implementation and rework In and after 2026: Writing software is extremely cheap, but it’s a wider phenomenon: generating output is effectively-free across many dimensions. Code is nearly free — if we have appropriate constraints. Designs are nearly free — if they follow patterns. Analysis is nearly free — if we’ve instrumented things properly Reworking software is extremely cheap. Historically industry has optimized around avoiding engineering rework because engineering was the highest cost / narrowest constraint. In many companies this was interpreted as writing code being the constraint, which was never true, but many common practices were designed as if that were true (e.g. bringing engineering into problem-solving late “to protect their time”) Working on the system is much more effective than historically if we get automated integration and feedback loops right, e.g. not improving a one-off design but improving the design system. Any place where improving the higher-leverage process is slower than solving the one-off is a bug in our process Explorer Pattern: primary-and-replicas metaphor The easiest metaphor to think about the Explorer Pattern is database replication. Databases like MySQL and PostgreSQL have a primary database, where writes are performed. Every write is verified at that point, and once it’s verified, you know that the writes will flow downstream to various secondary replicas. Those downstream replicas can be delayed but they can’t be wrong because writes are verified upstream. (I’ve resisted the desire to talk about the CAP theorem.) A different model for database design is that used by Dynamo or Cassandra (or MongoDB to a certain extent), where you have a replica set, and have to get an acknowledgement from the majority of the replica set for a write to be strongly consistent. This is a very reliable setup, because it means you can tolerate losing a node, but it also introduces inconsistencies, and on a fixed amount of hardware they tend to be much, much slower than running a primary-secondary setup (or rely on bad performance metrics that don’t fsync to disk to create the illusion of throughput). The Explorer Pattern is the former primary-secondary model, where the vast majority of the work is done by the working individual or team. This makes all work internally consistent because it’s passed through the same small group. It doesn’t, however, mean that the work is perfect. For example, you can always insert data that meets the table’s requirements but is still inherently wrong (e.g. 200 is a valid integer, but it doesn’t mean that my credit limit was supposed to be 200, that depends on the surrounding application logic). Other teams become aware of the changes downstream, not synchronously upfront, and it’s instead the working group’s responsibility to both rationalize approach and create visibility into their work for other teams to engage in a non-blocking fashion. Example: Support for Financial Aggregators A concrete example of this practice at Imprint was rolling out financial aggregator support, e.g. allowing folks to connect to their Imprint powered accounts via Plaid. This has always been something folks want, but it’s particularly important in the realm of agentic commerce where more folks’ agents are analyzing their financial state for them. For this project, one of our engineering leaders (Ron), built the first pass of the feature at a low-burn while understanding the shape of the problem in a private alpha. He chatted through some of the details periodically to keep other teams aware, but it was a bit of a side project. However, once he found the full shape of the problem and had implemented a full solution, we cut the replica-lag across teams down to near-zero, identified and ran through the small number of remaining issues, and shipped it. Like many of our projects this year, it was never officially on a roadmap, and shipped a quality feature that our members have wanted for some time. How to follow the Explorer pattern The rough rules for following the Explorer pattern: Know your goal and sponsor: every initiative ultimately has to have a specific outcome it’s pursuing and a sponsor who’s bankrolling that pursuit. This doesn’t always need to be explicit, especially for smaller projects, but once a project goes beyond ~3 weeks of effort, if you can’t very explicitly identify who the stakeholder is sponsoring your project and they would not enthusiastically agree, then you are likely closer to “lost” than “exploring” Small working group is small: at most 5 people, and preferably smaller. Everyone in the group has to keep the entire project in their head for as long as possible to detect problems and opportunities Small working group is flexible: folks in small working groups have to “find a way to yes” rather than “find a way to no”. Exploring is about uncovering the fundamental shape of a problem rather than pretending we know the fundamental shape Publish progress in a public channel: explorers have to report home with the progress they are making so others are aware. This is both a Linear Project and a Slack channel. Make the narrowest viable changes to what already exists: when we introduce unnecessary changes, we invalidate others’ mental models about how the world works. When we haven’t made those changes with care, we’re not only invalidating others’ mental model, we are creating the expectation that we’ve done it very intentionally for a good reason, which has a chilling effect on others improving them later, which is very expensive, whereas the Explorer pattern depends on being as inexpensive as possible Exercise good judgment to identify reasonable hypotheses: discard bad ideas immediately, and then filter the rest by trying to implement them as quickly as possible. Once you see the shape of the implementation, you can figure out which of the remainders are interesting Hold assumptions constant to avoid getting stuck: the only way to navigate complex ambiguous problems is to hold things constant, even when you know they are imperfect. For example, to do headcount planning we have to know our revenue, to know our revenue we have to forecast it, to forecast it we have to know the day that partners will go live next year. We don’t truly know any of those things, so just anchoring on a plausible guess to unblock us is much more valuable than trying to get them accurate. A little prework is useful, but a lot is just artificial precision that’s a distraction from progress Hold space for being totally wrong: when we move fast, with low information, we always find the way out, but often it’s not the way out we anticipated when we got started. Being open to throwing it all away, and starting a second, third, fourth time Ship all the way to production behind a feature flag: features and products move fast when we get the pieces working every step from frontend to backend to data pulls. This is the first step of exploration. Just make sure it’s behind a feature flag that’s only enabled for internal folks!
Comparing two different ways of work and working environments.
I own an old, cheap TV. It has no Internet connection, no fancy smart features that make you want to install a Pi-hole, and no ask-me-again-later updates. However, it is connected to my own desktop computer through an HDMI cable, so I can watch movies and TV series from the couch. Setting it up used […] The post Making a dumb TV just smart enough appeared first on Quentin Santos.
Five days and 540km on a bike across Kyushu, without a laptop. Notes on the peace of riding all day, convenience store dinners, and Japan's emptying countryside.