You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

如何为网站防复制脚本排除指定URL?

How to Exclude a Specific Tracking URL from Your Copy-Paste Blocking Script

Absolutely, you can tweak your existing scripts to make an exception for that tracking URL—let's adjust the code to let users copy/paste that specific content without restrictions. Here's how to do it:

1. Update the Right-Click (Context Menu) Block

Your original script blocks all right-clicks, but we can add a check to skip the restriction when the user interacts with your tracking link:

document.addEventListener('contextmenu', event => {
  // Replace this with your actual tracking URL
  const trackingUrl = 'https://your-tracking-url.com/track';
  
  // Check if the right-click is on or inside the tracking link
  const clickedTrackingLink = event.target.closest('a')?.href === trackingUrl;
  
  // Only block the context menu if it's NOT the tracking link
  if (!clickedTrackingLink) {
    event.preventDefault();
  }
});

2. Fix & Update the Copy/Cut/Paste Block

Your original copy/cut/paste code snippet was incomplete—let's expand it with the same exclusion logic:

// Define your tracking URL once for consistency
const trackingUrl = 'https://your-tracking-url.com/track';

// Loop through each event type we want to control
['copy', 'cut', 'paste'].forEach(eventName => {
  document.addEventListener(eventName, event => {
    // Check if the action is related to the tracking URL:
    // Either the target is the tracking link, or the selected content includes the URL
    const targetIsTrackingLink = event.target.closest('a')?.href === trackingUrl;
    const selectedContentIncludesTracking = window.getSelection().toString().includes(trackingUrl);
    
    // Only block the action if it has nothing to do with the tracking URL
    if (!targetIsTrackingLink && !selectedContentIncludesTracking) {
      event.preventDefault();
    }
  });
});

Quick Tips for Flexibility

  • If your tracking URL has dynamic parameters (like ?user=123), use includes() instead of strict equality: event.target.closest('a')?.href.includes(trackingUrl)
  • If the tracking content lives in a specific container (e.g., a <div class="tracking-box">), you can check for that instead: event.target.closest('.tracking-box')

That should do it—users will still be blocked from copying most content, but your tracking URL will work as intended.

内容的提问来源于stack exchange,提问作者Pascal

火山引擎 最新活动