Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Prevent it from showing barcode #25

Open
carles9000 opened this issue Mar 3, 2021 · 10 comments
Open

Prevent it from showing barcode #25

carles9000 opened this issue Mar 3, 2021 · 10 comments

Comments

@carles9000
Copy link

Hi,

How to execute a function without putting the barcode in any input?

Regardless of whether there is a focus or not, I only want to execute a function

Very good lib, congratulations
Carles

@fcaussa
Copy link

fcaussa commented Mar 9, 2021

Bump! Im looking the exact same request, being able to preventDefault onScan, to avoid being pasted/typed anywhere whether its been focused or not.

@ray73864
Copy link

+1 to this too, at present I have resorted to manually clearing the input text's value inside the onScan.

@jammin88
Copy link

+1 - preventDefault for successful onScan would be ideal.

@jammin88
Copy link

In case it helps anyone else...

The onScanError function gives you the key that was "rejected". So you can pass that to a function that handles keypresses

@laptopmutia
Copy link

anyone know how to this?

I want it only to execute the function instead giving input to any input

@konstantin-klima
Copy link

I've hacked it by checking the active input and removing the code that was written there during onScan.

  const element = <HTMLInputElement>document.activeElement
  if (element?.tagName.toLowerCase() === 'input') {
    element.value = element.value.replace(code, '')
  }

Not great, but works for my use case, until we get something better.

@laptopmutia
Copy link

laptopmutia commented Nov 29, 2022

I've hacked it by checking the active input and removing the code that was written there during onScan.

  const element = <HTMLInputElement>document.activeElement
  if (element?.tagName.toLowerCase() === 'input') {
    element.value = element.value.replace(code, '')
  }

Not great, but works for my use case, until we get something better.

where did you put this code? @konstantin-klima

@konstantin-klima
Copy link

I've hacked it by checking the active input and removing the code that was written there during onScan.

  const element = <HTMLInputElement>document.activeElement
  if (element?.tagName.toLowerCase() === 'input') {
    element.value = element.value.replace(code, '')
  }

Not great, but works for my use case, until we get something better.

where did you put this code? @konstantin-klima

Inside my event handler for OnScan:

function ReadCode(code, amount) {
const element = document.activeElement
    if (element?.tagName.toLowerCase() === 'input') {
        element.value = element.value.replace(code, '')
    }

    //Rest of logic
}

 document.addEventListener('scan', ReadCode)```

@sajith711
Copy link

sajith711 commented Nov 14, 2023

Even I need this request in my project. Please let me know if there is any way to do that using onScan.js,
@konstantin-klima I tried your approach but it is displaying the value for some time and then clearing the scanned value. I don't want that to happen.
I was trying from past two days but couldn't find a solution
Any help is highly appreciated.

Thanks

@markstuart
Copy link

markstuart commented Aug 21, 2024

I've found a bit of a hack for this:

  const focusedInput = () => {
    const focused = document.activeElement;
    return focused && ['INPUT', 'TEXTAREA'].includes(focused.tagName) ? focused : null;
  };

  const insertTextAtCursor = (focusedInput, text) => {
    const start = focusedInput.selectionStart ?? text.length;
    const end = focusedInput.selectionEnd ?? text.length;

    focusedInput.value = focusedInput.value.slice(0, start) + text + focusedInput.value.slice(end);
    focusedInput.selectionStart = focusedInput.selectionEnd = start + text.length;
  };

  const attachScan = () => {
    if (!onScan.isAttachedTo(document)) {
      let isCtrlCombo = false;
      onScan.attachTo(document, {
        onScan: (sCode: string) => {
          setScanned(sCode);
        },
        onKeyProcess(char, event) {
          // This callback has a `char` value for key events that are in the range
          // of valid scan characters. We capture the event so that any focused
          // input does not receive the character.

          // If the user is doing a ctrl-c/v/a etc, we don't want to capture the event
          // Store the state as a flag to check in onScanError
          isCtrlCombo = event.ctrlKey;
          const blockKeyStrokesFromFocusedInput = focusedInput() && char !== '' && !isCtrlCombo;
          if (blockKeyStrokesFromFocusedInput) {
            event.preventDefault();
          }
        },
        onScanError: (e: ScanValidationError) => {
          // Don't handle the error if there is no scan code
          if (e.scanCode === '') {
            return;
          }
          // If the character(s) fail the scan validation, we can update any
          // focused input with the characters we captured in onKeyProcess
          const focused = focusedInput();
          const updateFocusedInputWithFailedScanChars = focused && !isCtrlCombo;
          if (updateFocusedInputWithFailedScanChars) {
            insertTextAtCursor(focused, e.scanCode);
          }
        },
        // The following options are used to determine if a scan is valid
        // Need to keep these pretty tight to avoid the events that onKeyPress doesn't
        // block from being emitted before the scanError handler.
        // E.g. type a character then hit space, the space could be emitted before the character.
        timeBeforeScanTest: 15,
        avgTimeByChar: 10,
        minLength: 5,
      });
    }
  };

The key parts are the onKeyProcess and onScanError, and making sure the validation options are pretty tight. Had to handle copy/paste a bit differently too. Prevent the possible valid scan chars getting emitted to the focused input, and append them to the value on the focused input if they don't turn out to be part of a scan.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

8 participants