0Pricing
Browser Extensions Development (Chrome & Edge) · บทเรียน

การโต้ตอบกับข้อมูลหน้าเว็บ

ดึงข้อมูลจากหน้าเว็บ ตอบสนองต่อเหตุการณ์ของผู้ใช้บนหน้า และส่งข้อมูลกลับไปยังสคริปต์เบื้องหลังของคุณ

การโต้ตอบกับข้อมูลหน้าเว็บ เป็นบทเรียน Browser Extensions Development (Chrome & Edge) ฟรีบน CoddyKit นี่คือบทเรียนที่ 3 จากทั้งหมด 4 บทเรียน คุณสามารถอ่านบทเรียนทั้งหมดด้านล่างฟรี — จากนั้นลองปฏิบัติด้วยตัวคุณเองในเบราว์เซอร์พร้อมตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7 บทเรียนนี้เป็นส่วนหนึ่งของเส้นทางการเรียน Browser Extensions Development (Chrome & Edge) และความก้าวหน้าของคุณจะซิงค์ข้ามเว็บและแอป CoddyKit คอร์ส Browser Extensions Development (Chrome & Edge) มีบทเรียนทั้งหมด 4 บทเรียน

บางส่วนของบทเรียนนี้ยังไม่ได้รับการแปล และแสดงเป็นภาษาอังกฤษ

Intro: Interact with Web Data

Browser extensions can do more than just change how a web page looks. They can also interact with the data found on a web page!

This lesson explores how your extension can:

  • Extract information like text or values from a page.
  • Respond to user actions, such as clicks or typing.
  • Send this collected information back to your extension's background script for processing.

Let's make your extension smart about web page data!

Finding Elements on Page

To interact with data, you first need to locate the specific parts of the web page where that data resides. Your content scripts have access to the page's Document Object Model (DOM), just like regular JavaScript.

You'll use common methods to select elements:

  • document.getElementById("myId"): Finds an element by its unique ID.
  • document.querySelector(".myClass"): Finds the first element matching a CSS selector.
  • document.querySelectorAll("p.info"): Finds all elements matching a CSS selector, returning a NodeList.

Extracting Data: Text & Attributes

Once you've selected an element, you can easily extract its content or attributes. Here are key properties and methods:

  • element.innerText: Gets the visible text of an element and its children.
  • element.value: For input fields (<input>, <textarea>), gets the current user-entered value.
  • element.getAttribute("attrName"): Retrieves the value of a specific HTML attribute (e.g., href, src, data-id).

Try running this script to see how it grabs the page title.

console.log("Content script for data extraction loaded!");

// Get the page title
const pageTitle = document.title;
console.log("Page Title:", pageTitle);

// Try to get value from a hypothetical input field
// (This won't work without an actual input, but demonstrates the concept)
const searchInput = document.querySelector('input[type="search"]');
if (searchInput) {
  console.log("Search Input Value:", searchInput.value);
} else {
  console.log("No search input found to extract value from.");
}

Responding to User Events

Your extension can also react to user actions on the web page. This is crucial for creating interactive experiences.

You attach event listeners to elements using element.addEventListener(), just like in standard web development. Common events include:

  • 'click': When an element is clicked.
  • 'input': When the value of an input field changes.
  • 'submit': When a form is submitted.

This script adds a temporary button and logs when it's clicked.

console.log("Content script for event handling loaded!");

// Create a temporary button for demonstration
const tempButton = document.createElement('button');
tempButton.textContent = 'Click Me!';
tempButton.style.position = 'fixed';
tempButton.style.bottom = '50px';
tempButton.style.left = '10px';
tempButton.style.zIndex = '9999';
document.body.appendChild(tempButton);

// Add a click listener to the button
tempButton.addEventListener('click', () => {
  console.log("Temporary button clicked!");
  alert("You clicked the temporary button!");
});

Content to Background Messaging

Often, data extracted or events detected by a content script need to be sent to your extension's main logic in the background service worker for further processing or storage.

You send messages using chrome.runtime.sendMessage(). This function allows your content script to pass a JSON-serializable object (your data) to the background script.

The message object can contain any data you need to transfer, like extracted text or the type of user action.

Background Message Listener

For the background service worker to receive messages, it must set up a listener. This is done using chrome.runtime.onMessage.addListener().

The listener function receives three arguments:

  • message: The data object sent from the content script.
  • sender: Information about the sender (e.g., the tab ID).
  • sendResponse: A function to send a reply back to the content script.

Remember to return true from your listener if you plan to use sendResponse asynchronously.

Code: Interact & Send Data

Let's put it all together in a content script. This code adds a button to the page. When clicked, it extracts the page title and URL, then sends this information to the background script.

Run this code, then imagine your background script is waiting to receive this data!

console.log("Content script for interaction and sending loaded!");

// Create a button to trigger data extraction and sending
const sendDataButton = document.createElement('button');
sendDataButton.textContent = 'Send Page Data';
sendDataButton.style.position = 'fixed';
sendDataButton.style.bottom = '10px';
sendDataButton.style.right = '10px';
sendDataButton.style.zIndex = '10000';
sendDataButton.style.padding = '10px';
sendDataButton.style.backgroundColor = '#007bff';
sendDataButton.style.color = 'white';
sendDataButton.style.border = 'none';
sendDataButton.style.borderRadius = '5px';
sendDataButton.style.cursor = 'pointer';
document.body.appendChild(sendDataButton);

// Add event listener to the button
sendDataButton.addEventListener('click', () => {
  const pageTitle = document.title;
  const pageUrl = window.location.href;

  console.log("Button clicked! Preparing to send page data...");

  // Send message to background script
  chrome.runtime.sendMessage({
    action: "extractAndSendPageData",
    payload: {
      title: pageTitle,
      url: pageUrl
    }
  }, (response) => {
    if (response && response.status === "success") {
      console.log("Background confirmed data received.");
      alert("Page data sent to background!");
    } else {
      console.error("Error or no response from background:", response);
      alert("Failed to send data to background or no response.");
    }
  });
});

Code: Background Receives Data

This is the corresponding background service worker script. It sets up a listener for messages coming from any content script.

When it receives a message with the action: "extractAndSendPageData", it logs the extracted title and URL to its own console (which you can inspect in the browser's extension developer tools).

console.log("Background service worker initialized!");

chrome.runtime.onMessage.addListener(
  function(message, sender, sendResponse) {
    console.log("Received message from content script:", message);
    console.log("From tab:", sender.tab ? sender.tab.url : "unknown");

    if (message.action === "extractAndSendPageData") {
      console.log("Action identified: Page Data Extraction");
      console.log("Extracted Title:", message.payload.title);
      console.log("Extracted URL:", message.payload.url);

      // In a real extension, you might save this data to storage
      // or perform other background operations.

      // Send a success response back to the content script
      sendResponse({ status: "success", message: "Data received by background." });
      return true; // Indicates that sendResponse will be called asynchronously
    } else {
      console.log("Unknown message action:", message.action);
      sendResponse({ status: "error", message: "Unknown action type." });
    }
  }
);

Quick Check: Data Flow

Consider an extension that needs to know the text of a specific <div> element on a page when a user clicks a button, and then store that text.

Which sequence correctly describes the flow of information and actions?

Recap: Interacting with Data

Great job! You've learned how to make your extension truly interactive with web page data:

  • Finding Elements: Using DOM methods like getElementById and querySelector.
  • Extracting Data: Getting text with innerText or values with value, and attributes with getAttribute.
  • Handling Events: Responding to user actions like clicks using addEventListener.
  • Messaging: Sending extracted data from content scripts to background scripts via chrome.runtime.sendMessage and receiving it with chrome.runtime.onMessage.addListener.

This powerful combination opens up many possibilities for your extensions!

คำถามที่พบบ่อย

บทเรียน “การโต้ตอบกับข้อมูลหน้าเว็บ” ฟรีหรือไม่

ใช่ — ข้อความเต็มของ “การโต้ตอบกับข้อมูลหน้าเว็บ” ฟรีให้อ่านที่นี่บนเว็บ เพื่อปฏิบัติแบบโต้ตอบ (ตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7) และปลดล็อคส่วนที่เหลือของคอร์ส Browser Extensions Development (Chrome & Edge) ให้อัปเกรดเป็น CoddyKit PRO คอร์ส Browser Extensions Development (Chrome & Edge) มีบทเรียนทั้งหมด 4 บทเรียน

คุณจะเรียนรู้อะไรในบทเรียน “การโต้ตอบกับข้อมูลหน้าเว็บ”

ดึงข้อมูลจากหน้าเว็บ ตอบสนองต่อเหตุการณ์ของผู้ใช้บนหน้า และส่งข้อมูลกลับไปยังสคริปต์เบื้องหลังของคุณ คุณปฏิบัติ Browser Extensions Development (Chrome & Edge) ด้วยโค้ดที่ใช้งานได้จริงที่คุณเรียกใช้โดยตรงในเบราว์เซอร์ และติวเตอร์ AI ตลอด 24/7 ตอบคำถามของคุณขณะที่คุณไปผ่านบทเรียน

คุณต้องมีประสบการณ์ก่อนที่จะเริ่มเรียน Browser Extensions Development (Chrome & Edge) หรือไม่

ไม่จำเป็นต้องมีประสบการณ์มาก่อน Browser Extensions Development (Chrome & Edge) บน CoddyKit ออกแบบมาสำหรับผู้เริ่มต้นไปจนถึงผู้เรียนขั้นสูง คุณสามารถเริ่มต้นที่นี่หรือเริ่มจากตัวแรกและเรียนด้วยความเร็วของคุณเอง นี่คือบทเรียนที่ 3 จากทั้งหมด 4 บทเรียน

บทเรียน “การโต้ตอบกับข้อมูลหน้าเว็บ” ใช้เวลานานแค่ไหน

บทเรียน CoddyKit ส่วนใหญ่ใช้เวลาประมาณ 5–10 นาที แต่ละบทเรียนจึงสั้นและเป็นแบบโต้ตอบ คุณสามารถก้าวหน้าอย่างต่อเนื่องและกลับมาเรียนต่อจากตรงที่เพิ่งหยุดบนเว็บและแอปได้เลย

ฉันเขียนและรันโค้ดในบทเรียน Browser Extensions Development (Chrome & Edge) นี้ได้ไหม

ได้ บทเรียน Browser Extensions Development (Chrome & Edge) ทุกบทมีตัวแก้ไขโค้ดในตัว คุณจึงเขียนและรันโค้ดจริงได้เลยในเบราว์เซอร์ และได้รับข้อเสนอแนะจาก AI ในทันที — ไม่ต้องติดตั้งในเครื่องของคุณ

บทเรียนทั้งหมดในหลักสูตรนี้

  1. การแทรกสคริปต์เนื้อหา
  2. การปรับเปลี่ยน DOM ของหน้าเว็บ
  3. การโต้ตอบกับข้อมูลหน้าเว็บ
  4. การแทรก CSS และการจัดรูปแบบแบบแยกส่วน
← กลับไปที่ Browser Extensions Development (Chrome & Edge)