예제 프로그램

Browser SDK가 실제로 무엇을 보내는지 브라우저에서 바로 확인할 수 있는 단일 HTML 예제입니다.

CDN 스크립트 하나와 버튼 몇 개로 계측이 도는 것을 눈으로 확인하는 예제입니다. 설치 방식은 설치를, 각 버튼이 어떤 계측에 해당하는지는 계측을 참고하세요.

단일 HTML 페이지

index.html을 열고 아래 코드를 추가합니다. 만약 내부망 이슈로 인해 적절한 collector 주소가 설정되어 있지 않은 경우 오류가 발생하지만 브라우저 inspection 도구의 network 탭에서 Trace와 Log 데이터를 직접 확인해 볼 수 있습니다.

index.html
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Sophonz Browser SDK Test Example</title>
    <script
      src="https://cdn.sophonz.com/release/npm/@browser-sdk/latest/index.js"
      crossorigin="anonymous">
    </script>
    <script>
      SophonzSDK.init({
        collectorUrl: "https://in.sophonz.ai",
        appName: "your-app-name",
        appKey: "YOUR_APP_KEY",
        appVersion: "1.0.0"
      });
    </script>
  </head>
  <body>
    <h1>Sophonz Browser SDK Test Example</h1>
    <button id="work-btn">Do Work</button>
    <button id="error-btn">Throw Error</button>
    <button id="fetch-btn">Fetch Data</button>
    <button id="xhr-btn">XHR</button>
    <p>Click the buttons to test Sophonz tracing and error reporting.</p>
  </body>
  <script>
    // console instrumentation
    function doWork() {
      console.log("Work is done and span is ended");
    }
    // error instrumentation
    function throwError() {
      throw new Error("Test Error");
    }
    // xhr instrumentation
    function xhrBtn() {
      console.log("xhrBtn");
      const xhr = new XMLHttpRequest();
      xhr.open("GET", "https://jsonplaceholder.typicode.com/todos/1");
      xhr.onload = function () {
        if (xhr.status === 200) {
          console.log(xhr.response);
        }
      };
      xhr.send();
    }
    // fetch instrumentation
    function fetchBtn() {
      console.log("fetchBtn");
      fetch("https://jsonplaceholder.typicode.com/todos/1")
        .then(function (response) {
          return response.json();
        })
        .then(function (json) {
          console.log(json);
        });
    }
    // Attach event handlers
    window.onload = () => {
      document.getElementById("work-btn").addEventListener("click", () => {
        doWork();
      });
      document.getElementById("error-btn").addEventListener("click", () => {
        throwError();
      });
      document.getElementById("xhr-btn").addEventListener("click", () => {
        xhrBtn();
      });
      document.getElementById("fetch-btn").addEventListener("click", () => {
        fetchBtn();
      });
    };
  </script>
</html>