Skip to content

GM_xhr streams can't be canceled #1579

@derjanb

Description

@derjanb

Discussed in #1578

Originally posted by nikitanikolaev01081992 August 21, 2022
Hello,
I have troubles with closing stream from GM_xhr.
I use default reader for stream and it's method cancel.
After closing with this way the script of tampermonkey is crashed.
Can you please provide instructions with proper way of closing GM_xhr's stream?

image

const unsubscribeStreamButton = document.querySelector('button');

new Promise((resolve, reject) => {
  GM_xmlhttprequest({
    method: 'GET', 
    url: '<WORKING_URL>', 
    responseType: 'stream'
    onreadystatechange: (data) => {
      if (data.readyState !== 2) {
        return;
      }
      resolve(data.response);
    },
    onerror: () => {reject('Something wrong')}
  })
})
.then(async (stream) => {
  const reader = stream.getReader();
  unsubscribeStreamButton.addEventListener('click', () => reader.cancel());
  
  while(true) {
    const {done, value} = await reader.read();
    
    if (done) {
      break;
    }
    
    console.log(value);
  }
  reader.cancel();
})
.catch((error) => console.log(error));

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions