You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JavaScript书签小工具开发求助:如何为URL添加0-前缀及后缀域名

Fixing Your Library Bookmarklet: Adding the 0- Prefix Correctly

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

  1. Parse the current URL: The URL object takes the full current page URL and splits it into easy-to-access parts (protocol, hostname, path, etc.).
  2. Modify the hostname: We directly update the hostname property by prepending 0- and appending your library's suffix. No messy string replacements that break the protocol!
  3. Redirect: Convert the modified URL object 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 09:48:28