javascript Content-Typeを取得する

javascript Content-Typeを取得する

javascriptで、Content-Typeを取得するサンプルコードを記述してます。

環境

  • OS windows10 pro 64bit
  • Apache 2.4.43
  • ブラウザ chrome 104.0.5112.101

Content-Typeを取得

「document.contentType」を使用することで、取得することが可能です。

const dc = document.contentType;

console.log(dc);
// text/html

実行結果

「document.contentType」は、ie11では、取得することができません。

サンプルコード

以下は、
「実行」ボタンをクリックすると、Content-Typeを取得して表示するだけの
サンプルコードとなります。

※cssには「tailwind」を使用してます。

<!DOCTYPE html>
<html lang="ja">

<head>
  <meta charset="utf-8">
  <title>mebeeサンプル</title>
  <link href="https://unpkg.com/tailwindcss@^1.0/dist/tailwind.min.css" rel="stylesheet">
</head>

<script>

  const hoge = () => {
    // contentTypeを表示
    result.innerHTML = document.contentType;

  }

  window.onload = () => {
    // クリックイベントを登録
    btn.onclick = () => { hoge() }; // document.getElementById('btn');を省略    
  }

</script>

<body>
  <div class="container mx-auto my-56 w-56 px-4">

    <div class="flex justify-center">
      <p id="result" class="bg-purple-700 text-white py-2 px-4 rounded-full mb-3 mt-4">Content-Type</p>
    </div>

    <div class="flex justify-center">
      <button id="btn" type="button"
        class="mt-5 bg-transparent border border-red-500 hover:border-red-300 text-red-500 hover:text-red-300 font-bold py-2 px-4 rounded-full">
        実行
      </button>
    </div>
  </div>

</body>

</html>

「contentType」が取得されていることが確認できます。