如何用JavaScript获取外部页面的<title>标签内容(Zapier环境)
Hey there! Let's work through this together since you're learning JS and navigating Zapier's specific constraints (Node.js v4.3.2, no extra libraries, mandatory callback for async code).
First, let's clarify what those then functions are doing in the original example:
- The first
thentakes the raw response fromfetchand converts it into plain text (since we're dealing with HTML, which is just a string of text). This returns another Promise, so we chain a secondthento handle that text. - The second
thenreceives the full HTML string, which is where we'll extract the<title>instead of returning the whole page.
Since we can't use DOM parsers (like document.querySelector) in Node.js v4.3.2, a reliable (and lightweight) way to grab the title is with a regular expression. Here's a complete, Zapier-compliant script that does exactly what you need:
// Pull the target URL from Zapier's input (configure this field in your Zap setup!) const targetUrl = inputData.url; fetch(targetUrl) // Step 1: Convert the HTTP response to raw HTML text .then(response => { // First, make sure the request succeeded (status code 200-299) if (!response.ok) { throw new Error(`Request failed with status: ${response.status}`); } return response.text(); }) // Step 2: Extract the title from the HTML string .then(html => { // Regex to match the title tag (case-insensitive, handles line breaks inside the tag) const titleMatch = html.match(/<title>([\s\S]*?)<\/title>/i); let pageTitle = "No title found"; if (titleMatch && titleMatch[1]) { // Trim extra whitespace/newlines from the title text pageTitle = titleMatch[1].trim(); } // Zapier requires using callback for async code: // - First parameter = error (null means no error) // - Second parameter = data to pass to the next Zap step callback(null, { extractedTitle: pageTitle }); }) // Catch any errors (network issues, HTTP failures, title extraction problems) .catch(error => { callback(error); });
Key details to note:
inputData.url: This lets you dynamically specify any external page URL in your Zap's setup (no hardcoding!). Just add an input field named "url" in the Zapier Code app configuration.- Response check: The
response.okcheck ensures we don't try to process broken or failed requests (like 404s or 500s). - Regex explanation:
[\s\S]*?matches every character (including line breaks) in a non-greedy way—this prevents it from accidentally matching multiple tags if the HTML is messy. Theiflag makes the match case-insensitive (so<TITLE>or<Title>work too). - Callback requirement: Zapier's Code app relies on the
callbackfunction to handle async results. Passnullas the first argument when everything works, and the error object if something goes wrong.
This approach avoids relying on third-party APIs (which you said were unstable) and sticks strictly to Zapier's Node.js v4.3.2 environment rules.
内容的提问来源于stack exchange,提问作者Robert Andrews

