特定URL加载时执行JavaScript异常:仅首页触发弹窗问题求助
Hey there! Let's sort out why your alert is only popping up on the homepage instead of your cart page:
1. The Core Operator Mistake
Your if statement uses a single equals sign (=), which is an assignment operator—it’s actually setting currURL to the cart URL instead of checking if they’re equal. That’s why your code was behaving unpredictably. You need to use a strict equality check (===) instead, which compares both the value and data type of the two URLs.
2. Quick Best Practice: Capture URL When Needed
While not the main issue here, defining currURL outside the codeAddress function means it only grabs the URL once when the script first loads. For consistency (especially if you ever work with single-page apps where URLs change without reloading), move the URL capture inside the function to get the current, up-to-date URL every time it runs.
Corrected Code
Here’s the fixed version of your script that will trigger correctly on the cart page:
function codeAddress() { // Grab the current URL inside the function to ensure it's always fresh const currURL = window.location.href; // Use strict equality check (===) instead of assignment (=) if (currURL === 'https://www.example.com/cart'){ alert('We are not shipping to countries that are not listed in shipping country!'); } } window.onload = codeAddress;
Extra: Handle URLs with Query Parameters
If your cart URL might have extra parameters (like https://www.example.com/cart?item=123), the exact match above won’t work. Instead, you can check if the URL contains the cart path using includes():
function codeAddress() { const currURL = window.location.href; if (currURL.includes('/cart')){ alert('We are not shipping to countries that are not listed in shipping country!'); } } window.onload = codeAddress;
This should make your alert fire exactly when users are on the cart page.
内容的提问来源于stack exchange,提问作者Emma Expat

