Skip to content

@match handling doesn't follow script standard #314

@xentac

Description

@xentac

According to Tampermonkey you must include a protocol when defining a @match meta (https://www.tampermonkey.net/documentation.php?locale=en#meta:match).

The current code (

matches.any((match) => (match == "*" || url.contains(match.replaceAll("*", ""))));
) doesn't handle globs very well either. If you define a * anywhere in the middle of a URL, it will not match any URL you actually want it to.

I asked chatgpt to implement a @match handler and it suggested code like this:

function matchPattern(pattern, url) {
  // Escape regex special characters except * (we'll handle * ourselves)
  function escapeRegex(str) {
    return str.replace(/[$^+.?()[\]{}|\\]/g, '\\$&');
  }

  // Convert @match pattern to regex
  function patternToRegex(pattern) {
    const match = pattern.match(/^(https?|file|\*):\/\/([^\/]*)\/(.*)$/);
    if (!match) throw new Error('Invalid @match pattern: ' + pattern);

    const [, scheme, host, path] = match;

    // Scheme
    let schemeRegex = scheme === '*' ? 'https?' : escapeRegex(scheme);

    // Host
    let hostRegex = host
      .replace(/\./g, '\\.')
      .replace(/^\*\./, '(?:[^/]+\\.)?') // *.example.com => optional subdomain
      .replace(/\*/g, '[^/]*'); // wildcard in host (unusual)

    // Path
    let pathRegex = escapeRegex(path).replace(/\*/g, '.*');

    return new RegExp(`^${schemeRegex}://${hostRegex}/${pathRegex}$`);
  }

  const regex = patternToRegex(pattern);
  return regex.test(url);
}

Whether or not you want to break scripts that don't include the protocol in torn pda is up to you, but you could modify the final RegExp to make the scheme optional.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions