Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> JavaScript

วิธีแสดงรายการ Plugins ที่ติดตั้งใน Browser ด้วย JavaScript

ใช้ navigator.plugins

navigator.plugins เป็น Array-like Object มี Entry สำหรับแต่ละ Plugin ที่ติดตั้ง

ตัวอย่างโค้ด

<html>
<head>
  <title>List of Plug-Ins</title>
</head>
<body>
  <table border="1">
    <tr>
      <th>Plug-in Name</th>
      <th>Filename</th>
      <th>Description</th>
    </tr>
    <script>
      for (let i = 0; i < navigator.plugins.length; i++) {
        const plugin = navigator.plugins[i];
        document.write("<tr><td>" + plugin.name + "</td><td>");
        document.write(plugin.filename + "</td><td>");
        document.write(plugin.description + "</td></tr>");
      }
    </script>
  </table>
</body>
</html>

เวอร์ชันสมัยใหม่ (ES6+)

// ใช้ for...of loop
const table = document.createElement('table');
table.innerHTML = `
  
    NameFilenameDescriptionMIME Types
  
  
    ${[...navigator.plugins].map(plugin => `
      
        ${plugin.name}
        ${plugin.filename || 'N/A'}
        ${plugin.description}
        ${[...plugin.mimeTypes].map(m => m.type).join(', ')}
      
    `).join('')}
  
`;
document.body.appendChild(table);

ผลลัพธ์ใน Browser สมัยใหม่ (2024+)

เนื่องจาก NPAPI Plugins ถูก Remove แล้ว ผลลัพธ์มักจะเป็น:

  • Chrome: "Chrome PDF Viewer", "Chromium PDF Viewer", "Widevine Content Decryption Module"
  • Firefox: "openpdf" (PDF.js), "Widevine Content Decryption Module"
  • Safari: Built-in PDF, éventuellement d'autres
  • Array อาจว่างเปล่าหรือมีแค่ Built-ins

ตัวอย่าง Output (Chrome)

Name: Chrome PDF Viewer
Filename: internal-pdf-viewer
Description: Portable Document Format
MIME Types: application/pdf

Name: Chromium PDF Viewer
Filename: internal-pdf-viewer
Description: Portable Document Format
MIME Types: application/pdf

Name: Widevine Content Decryption Module
Filename: widevinecdmadapter
Description: Enables Widevine licenses for playback of HTML audio/video
MIME Types: application/x-ppapi-widevine-cdm

ข้อควรระวัง

  • document.write ใน Loop ภายใน Table อาจทำให้ HTML Invalid (Browser จะย้าย Script นอก Table) ควรสร้าง DOM Elements แทน
  • Plugin Detection ไม่เชื่อถือได้สำหรับ Feature Detection ควรใช้ Capability Detection แทน
  • Privacy: Fingerprinting ผ่าน Plugin List เป็นเรื่องที่มีจริง

ทางเลือกที่ดีกว่า: Feature Detection

// แทนที่จะเช็ค Plugin ให้เช็ค Feature โดยตรง
if (typeof PDFJS !== 'undefined') { /* PDF Support */ }
if ('mediaCapabilities' in navigator) { /* Media Capabilities */ }
if ('showOpenFilePicker' in window) { /* File System Access */ }

สรุป

ใช้ navigator.plugins แสดงรายการ Plugins แต่ใน Browser สมัยใหม่มีแค่ Built-ins (PDF, Widevine) NPAPI Deprecated แล้ว ควรใช้ Feature Detection แทน