开发Chrome右键跳转Reddit到redditp扩展时遇contextMenus.create无效URL模式错误
Got it, let's break down what's causing that "Invalid url pattern" error and fix your extension.
First off, looking at your code snippet, it looks like you started adding a targetUrlPatterns parameter to chrome.contextMenus.create but left it unfinished ("target...). Chrome's context menu API expects this parameter to be an array of valid URL patterns if you want to restrict the menu to specific links—and if you mess up the pattern format or leave the parameter incomplete, you'll get that exact error.
Here's the corrected full code for your background.js:
function redpts(info, tab) { var url = info.linkUrl; // Handle cases where selectionText might be undefined console.log(`Link ${info.selectionText || "Reddit subreddit"} was clicked to be redditp'd.`); var urlp = url.replace(/reddit.com/i, "redditp.com"); chrome.tabs.create({ url: urlp }); } chrome.contextMenus.create({ "title": "RedditP That Shizz!", "type": "normal", "contexts": ["link"], // Correct URL pattern to match any Reddit link (subdomains included) "targetUrlPatterns": ["*://*.reddit.com/*"], // Bind your click handler function "onclick": redpts });
Key fixes explained:
- Completed
targetUrlPatterns: The pattern"*://*.reddit.com/*"tells Chrome to only show this menu on links pointing to any subdomain of reddit.com (e.g.,www.reddit.com,old.reddit.com) with any path. This follows Chrome's required URL pattern format:*://matches any protocol (http/https)*.reddit.commatches reddit.com and all its subdomains/*matches any path after the domain
- Added
onclickbinding: Your original code didn't explicitly link theredptsfunction to the menu's click event—this ensures the function runs when the user selects the menu option. - Safeguarded
selectionText: If the user right-clicks a link without selecting text,info.selectionTextwill be undefined. The||operator falls back to a default string to avoid messy console logs.
Don't forget your manifest.json permissions!
To make this work, your manifest needs the right permissions (especially if you're using Manifest V3, which is the current standard):
{ "manifest_version": 3, "name": "RedditP Redirect", "version": "1.0", "background": { "service_worker": "background.js" }, "permissions": ["contextMenus", "tabs"], "host_permissions": ["*://*.reddit.com/*", "*://*.redditp.com/*"] }
contextMenus: Required to create the right-click menu optiontabs: Needed to create a new tab with the redirected URLhost_permissions: Allows the extension to interact with Reddit and RedditP domains
That should resolve the "Invalid url pattern" error and get your extension working as intended—right-click any Reddit link, select your menu option, and it'll open the RedditP version in a new tab.
内容的提问来源于stack exchange,提问作者Slid3r

