如何根据浏览器标签页活跃状态修改Shopify页面标题?
Fix for Shopify Tab Title Change Script
Let's walk through the issues in your code and get it working properly:
Key Problems in Your Original Code
- Wrong Title Property: You used
page.title, but the correct way to modify the browser tab title is withdocument.title. That's the main reason your script wasn't updating the title. - Unsafe Variable Declarations: Your
leftTitleandbackTitlevariables weren't declared withvar,let, orconst, which can cause unexpected behavior with global scope. - jQuery Dependency Risk: If your Shopify theme doesn't load jQuery before your script runs, the
$function will throw an error (though most themes do include jQuery by default).
Solution 1: Corrected jQuery Version
If your theme already uses jQuery, replace your code with this fixed version:
<script> $(function() { const leftTitle = 'Message A'; // Title when tab is inactive const backTitle = 'Message B'; // Title when tab is active $(window).blur(function() { document.title = leftTitle; }); $(window).focus(function() { document.title = backTitle; }); }); </script>
Quick Note: Make sure this script is placed after jQuery loads in your theme.liquid file. Most themes load jQuery early in the <head> section, so adding this right before the closing </head> tag should work perfectly.
Solution 2: Vanilla JavaScript (No jQuery Needed)
For maximum compatibility (and to avoid relying on jQuery), use this native browser API version:
<script> document.addEventListener('DOMContentLoaded', function() { const leftTitle = 'Message A'; // Title when tab is inactive const backTitle = 'Message B'; // Title when tab is active window.addEventListener('blur', function() { document.title = leftTitle; }); window.addEventListener('focus', function() { document.title = backTitle; }); }); </script>
This works without any external dependencies, so it's guaranteed to run regardless of your theme's setup.
How to Test
- Save your changes to
theme.liquidand preview your store. - Switch to another browser tab (inactive state) – the title should update to "Message A".
- Switch back to your store's tab (active state) – confirm it changes to "Message B".
内容的提问来源于stack exchange,提问作者abelvf
相关产品推荐
相关产品推荐

