Clipboard Transformation JavaScript works ONLY when testing

Describe the bug

If I copy the following URL

https://community.folivora.ai/top?period=weekly

and paste it with my JavaScript Clipboard Transformation (below) it does not work in a real app. But when I go into the configuration and test the JavaScript, everything works as expected.

Since it is not possible for bad code to randomly generate the right result, I know the code works, and the testing system works. So the bug appears to be that the Clipboard Transformation is failing to paste any result at all. Alternately there might be some difference in the way the JavaScript is being run in real-world applications that changes the result. Of course there might be other points at which there is a failure which I can't imagine since I don't know anything of the inner workings of BTT.

Here is the JavaScript:

async (clipboardText) => {
  const urlPattern = /^(https?:\/\/[^?#]+)(\?[^#]*)?(#.*)?$/;
  const match = clipboardText.match(urlPattern);

  if (!match) {
    console.error("Invalid URL format:", clipboardText);
    return clipboardText; // Return original if it's not a valid URL
  }

  const baseUrl = match[1];
  const queryString = match[2] ? match[2].substring(1) : '';
  
  // Blacklist e.g. key patterns used to track users
  const blacklistPattern = /^utm.*/i;
  // Whitelist array for commonly used search query parameters
  const whitelist = ['q', 'query', 'search', 'p', 'text'];   
  // Set to true to remove non-whitelisted items
  const removeUnknowns = true;

  if (!queryString) return baseUrl;

  let cleanedParams = [];
  
  queryString.split('&').forEach(param => {
    const [key, value] = param.split('=');

    if (blacklistPattern.test(key)) {
      return;
    }
    if (!whitelist.includes(key) && removeUnknowns) {
      return;
    }
    cleanedParams.push(`${key}=${value}`);
  });

  const cleanedQueryString = cleanedParams.join('&');
  return cleanedQueryString ? `${baseUrl}?${cleanedQueryString}` : baseUrl;
}

The input format is "public.utf8-plain-text"
The output format is "Plain Text"

Screenshots


Device information:

  • Type of Mac: 2020 MacBook Air M1
  • macOS version: 15.3.1 (24D70)
  • BetterTouchTool version: 5.242

Additional information (e.g. crash logs, related issues, etc.):

Maybe there is some misunderstanding for the action you use:

"Transform & Replace Selection With Java Script" will copy whatever text is currently selected, run it through your transformer and replace that selected text with the transformer result. If nothing is selected at that moment it will not work.

From your description it sounds like you'd want the other action
"Transform Clipboard Contents With Java Script"