为何出现'Uncaught TypeError: Cannot read property 'match' of undefined'?(页面链接追加查询字符串)
Hey there! Let's break down why this error pops up when you deploy your script to a live page (even though it worked perfectly in CodePen) and how to fix it.
First, Let's Pinpoint the Error Sources
That error is telling us one of two edge cases is happening on your live page that didn't occur in CodePen:
- Either
string_matchisundefined/null(meaning your regex didn't find any query string in the current page's URL) - Or some
<a>elements on the page don't have a validhrefattribute (sohrefisundefinedwhen you try to run.match()on it)
Solution 1: Guard Against Missing Query Strings
First, let's make sure we only try to append a query string if we actually found one in the current page URL. Add a safety check before processing links:
// Get current page URL and extract query string const currentUrl = window.location.href; const string_match = currentUrl.match(/\?(.*)$/); // Only proceed if we found a valid query string if (!string_match || !string_match[1]) { console.log("No query string found in current URL, skipping link updates."); return; } const queryString = string_match[1];
Solution 2: Filter Out Invalid Links
Next, when looping through page links, we need to skip any links that don't have a valid, usable href. We can add checks to ensure we're only working with real web links (and skip things like javascript:void(0), mailto: or empty hrefs):
// Loop through all links document.querySelectorAll('a').forEach(link => { const href = link.href; // Skip links with no href, or non-web link types if (!href || href.startsWith('javascript:') || href.startsWith('mailto:') || href.startsWith('tel:')) { return; } // Now safely check for existing query string and append const newHref = href + (href.match(/\?/) ? '&' : '?') + queryString; link.href = newHref; });
Putting It All Together (Full Fixed Script)
Here's the combined, robust version of your script that handles both edge cases:
(function() { const currentUrl = window.location.href; const string_match = currentUrl.match(/\?(.*)$/); // Exit early if no query string exists if (!string_match || !string_match[1]) { return; } const queryString = string_match[1]; document.querySelectorAll('a').forEach(link => { const href = link.href; // Skip invalid/non-web links if (!href || !href.startsWith('http')) { return; } // Update the href with the query string (using includes for cleaner readability) link.href = href + (href.includes('?') ? '&' : '?') + queryString; }); })();
Why This Worked in CodePen but Not Your Live Page
CodePen's test environment probably had:
- A URL that always included a query string (so
string_matchwas never null) - Only valid
<a>elements with properhrefattributes (no broken or non-web links)
Your live page likely has at least one of these edge cases that CodePen didn't encounter.
内容的提问来源于stack exchange,提问作者DXC

