You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JavaScript中与PHP的file_get_contents等效的方法是什么?

Equivalent to PHP's file_get_contents in Tampermonkey JavaScript

Hey there! Since you're building a Tampermonkey script and can't rely on PHP, let's break down the JavaScript methods that do exactly what file_get_contents does—fetch a webpage's content as a raw string.

1. Using the Standard fetch API

If you're targeting modern browsers (which Tampermonkey fully supports), the fetch API is the cleanest, most modern way to grab page content. It uses promises, so we'll use async/await for readability:

async function fetchPageContent(url) {
  try {
    const response = await fetch(url);
    // Check if the request succeeded
    if (!response.ok) {
      throw new Error(`Request failed with status: ${response.status}`);
    }
    // Get the content as a raw string (just like file_get_contents)
    const content = await response.text();
    return content;
  } catch (error) {
    console.error('Failed to fetch content:', error);
    return null;
  }
}

// How to use it:
fetchPageContent('https://example.com').then(content => {
  if (content) {
    console.log('Got page content:', content);
    // Add your content processing logic here
  }
});

Note: The standard fetch is subject to the same-origin policy. That means if you're trying to fetch content from a different domain than the one your script is running on, it might get blocked by CORS. For cross-domain requests, Tampermonkey has a better tool...

2. Using Tampermonkey's GM_xmlhttpRequest

Tampermonkey provides a built-in API called GM_xmlhttpRequest that bypasses CORS restrictions, making it ideal for grabbing content from external sites. This is probably your best bet for most userscript scenarios.

First, you need to grant permission to use this API at the top of your Tampermonkey script:

// ==UserScript==
// @name         Your Script Name
// @namespace    your-namespace
// @version      0.1
// @description  Fetch content like file_get_contents
// @author       You
// @match        https://your-target-site.com/*
// @grant        GM_xmlhttpRequest  // Required for this API!
// ==/UserScript==

Then use the function like this:

function getPageContent(url) {
  return new Promise((resolve, reject) => {
    GM_xmlhttpRequest({
      method: 'GET',
      url: url,
      onload: function(response) {
        if (response.status >= 200 && response.status < 300) {
          // response.responseText holds the raw string content
          resolve(response.responseText);
        } else {
          reject(new Error(`Request failed: ${response.status} ${response.statusText}`));
        }
      },
      onerror: function(error) {
        reject(new Error('Network error occurred:', error));
      }
    });
  });
}

// Usage example:
getPageContent('https://external-site.com')
  .then(content => {
    console.log('Fetched content:', content);
    // Process the content here
  })
  .catch(error => {
    console.error('Error:', error);
  });

Key Differences to Note

  • fetch is standard JavaScript, but restricted by CORS. Use this if you're fetching content from the same domain as your script's @match target.
  • GM_xmlhttpRequest is Tampermonkey-specific, bypasses CORS, and works for any domain—this is the go-to for most userscript scenarios where you need to pull content from external sites.

Both methods will give you the raw text content of a webpage, just like PHP's file_get_contents does. Pick the one that fits your use case!

内容的提问来源于stack exchange,提问作者frosty

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 04:10:33