简体   繁体   中英

How can I call Web APIs in React JSX?

I'm writing a music player with React and Electron and want to add metadata for the audio so as I can get MPRIS support. So I did some searching and found Media Session API is what I needed. To test it, I copied the code from the exmaple code contained by the above link into a function in my project.

  navigator.mediaSession.metadata = new MediaMetadata({
    title: 'Unforgettable',
    artist: 'Nat King Cole',
    album: 'The Ultimate Collection (Remastered)',
    artwork: [
      { src: 'https://dummyimage.com/96x96',   sizes: '96x96',   type: 'image/png' },
      { src: 'https://dummyimage.com/128x128', sizes: '128x128', type: 'image/png' },
      { src: 'https://dummyimage.com/192x192', sizes: '192x192', type: 'image/png' },
      { src: 'https://dummyimage.com/256x256', sizes: '256x256', type: 'image/png' },
      { src: 'https://dummyimage.com/384x384', sizes: '384x384', type: 'image/png' },
      { src: 'https://dummyimage.com/512x512', sizes: '512x512', type: 'image/png' },
    ]
  });

I put it into a function that a component will call when the next song is played.However, I got errors like this:

Failed to compile.

./src/components/FM/Cover/index.jsx
  Line 112:  'MediaMetadata' is not defined  no-undef

Search for the keywords to learn more about each error.

Why?

You need to reference the window object.

window.MediaMetadata
^^^^^^

This is because babel/es-lint does not know MediaMetadata exists and will throw an error. Since Chrome injects this object as a global variable, it is accessible via the window object.

(re-posting what @AngelSalazar said in the comments of the OP for ease of use)

/* eslint-disable-next-line */
navigator.mediaSession.metadata = new MediaMetadata({
  title: 'Unforgettable',
  artist: 'Nat King Cole',
  album: 'The Ultimate Collection (Remastered)',
  artwork: [
    { src: 'https://dummyimage.com/96x96',   sizes: '96x96',   type: 'image/png' },
    { src: 'https://dummyimage.com/128x128', sizes: '128x128', type: 'image/png' },
    { src: 'https://dummyimage.com/192x192', sizes: '192x192', type: 'image/png' },
    { src: 'https://dummyimage.com/256x256', sizes: '256x256', type: 'image/png' },
    { src: 'https://dummyimage.com/384x384', sizes: '384x384', type: 'image/png' },
    { src: 'https://dummyimage.com/512x512', sizes: '512x512', type: 'image/png' },
]
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM