JavaScript书签小工具开发求助:如何为URL添加0-前缀及后缀域名
Hey there, I see you're close to getting your bookmarklet working—great start with the suffix! The issue with adding the 0- prefix is that your current code is messing with the full origin (which includes the https:// protocol), leading to invalid URL structure that throws errors. Let's break this down and fix it properly.
The Root Problem
Your original code uses l.origin (e.g., https://www.database.com) and tries to modify it directly. Adding 0- before that would create something like https://0-https://www.database.com...—which is obviously broken. Instead, we need to target just the hostname part of the URL (the www.database.com bit) to add both the prefix and suffix.
The Solution: Use the URL API for Clean Parsing
The browser's built-in URL object makes it trivial to split and modify URL components without manual string hacks. Here's the updated bookmarklet code that handles both the 0- prefix and the library suffix correctly:
javascript:(function(){ const currentUrl = new URL(location.href); // Modify the hostname: add 0- prefix and library suffix currentUrl.hostname = `0-${currentUrl.hostname}.elibrary.qatar-weill.cornell.edu`; // Redirect to the modified URL location.href = currentUrl.toString(); })();
How This Works
- Parse the current URL: The
URLobject takes the full current page URL and splits it into easy-to-access parts (protocol, hostname, path, etc.). - Modify the hostname: We directly update the
hostnameproperty by prepending0-and appending your library's suffix. No messy string replacements that break the protocol! - Redirect: Convert the modified
URLobject back to a string and set it as the new location.
Example Test
- Original URL:
https://www.database.com/article-link - Modified hostname:
0-www.database.com.elibrary.qatar-weill.cornell.edu - Final URL:
https://0-www.database.com.elibrary.qatar-weill.cornell.edu/article-link
This will work for URLs with or without the www. prefix, and it preserves all path, query, and hash parts of the original URL (so if your article link has parameters like ?page=2, those will stay intact!).
内容的提问来源于stack exchange,提问作者Zain Burney

