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

如何通过SOQL或REST API实现Chrome插件获取Salesforce当前选中对象

Reliably Get Current Salesforce Object via REST API (Instead of DOM Scraping)

Great question—DOM scraping is super fragile with Salesforce because their UI can shift between releases, customizations, or even different Lightning Experience layouts. Using Salesforce's official REST API is the way to go for long-term stability. Here's a step-by-step breakdown:

Step 1: Extract the Current Object's API Name from the URL

First, you don't need DOM hacks to identify the object—Salesforce encodes it directly in the page URL. For example:

  • Record detail page: https://your-domain.lightning.force.com/lightning/r/Account/001D000000K0fXOIAZ/view
  • Object list view: https://your-domain.lightning.force.com/lightning/o/Account/list
  • Object setup page: https://your-domain.lightning.force.com/lightning/setup/ObjectManager/Account/FieldsAndRelationships/list

You can parse this URL with a simple JavaScript function to grab the object API name reliably:

function getCurrentSObjectApiName() {
  const urlSegments = window.location.pathname.split('/');
  // Handle record pages (lightning/r/ObjectApiName/RecordId/...)
  if (urlSegments.includes('lightning')) {
    const rIndex = urlSegments.indexOf('r');
    const oIndex = urlSegments.indexOf('o');
    if (rIndex !== -1 && rIndex + 1 < urlSegments.length) {
      return urlSegments[rIndex + 1];
    } else if (oIndex !== -1 && oIndex + 1 < urlSegments.length) {
      return urlSegments[oIndex + 1];
    }
    // Handle setup pages (ObjectManager/ObjectApiName/...)
    const managerIndex = urlSegments.indexOf('ObjectManager');
    if (managerIndex !== -1 && managerIndex + 1 < urlSegments.length) {
      return urlSegments[managerIndex + 1];
    }
  }
  return null;
}

Step 2: Authenticate Your Chrome Plugin with Salesforce's Session ID

To call the REST API, you need a valid Salesforce session ID (sid). You can retrieve this via Chrome's cookies API—just make sure your plugin's manifest.json includes the required permissions:

manifest.json permissions snippet:

{
  "permissions": ["cookies"],
  "host_permissions": ["https://*.salesforce.com/*"]
}

Then fetch the session ID with this async function:

async function getSalesforceSessionId() {
  const cookie = await chrome.cookies.get({
    url: window.location.origin,
    name: 'sid'
  });
  return cookie ? cookie.value : null;
}

Step 3: Fetch Object Metadata via the SObject Describe API

Salesforce's SObject Describe REST API returns all critical metadata for an object—labels, fields, record types, user permissions, and more. Use this endpoint: https://your-domain/services/data/vXX.X/sobjects/{ObjectApiName}/describe/

Replace vXX.X with the latest stable API version (e.g., v59.0). Here's how to call it:

async function getSObjectDetails(objectApiName) {
  const sid = await getSalesforceSessionId();
  if (!sid || !objectApiName) return null;

  const apiVersion = 'v59.0';
  const endpoint = `${window.location.origin}/services/data/${apiVersion}/sobjects/${objectApiName}/describe/`;

  try {
    const response = await fetch(endpoint, {
      headers: {
        'Authorization': `Bearer ${sid}`,
        'Content-Type': 'application/json'
      }
    });
    if (!response.ok) throw new Error(`API request failed: ${response.statusText}`);
    return await response.json();
  } catch (error) {
    console.error('Error fetching object details:', error);
    return null;
  }
}

Step 4: (Optional) Query Specific Record Data with SOQL

If you need details about the selected record (not just the object itself), extract the record ID from the URL (using a similar method to the object API name) and use the Query API with SOQL:

async function getRecordDetails(objectApiName, recordId) {
  const sid = await getSalesforceSessionId();
  if (!sid || !objectApiName || !recordId) return null;

  const apiVersion = 'v59.0';
  // Example SOQL: Fetch key fields for the record
  const soql = `SELECT Name, CreatedDate, LastModifiedDate FROM ${objectApiName} WHERE Id = '${recordId}'`;
  const encodedSoql = encodeURIComponent(soql);
  const endpoint = `${window.location.origin}/services/data/${apiVersion}/query?q=${encodedSoql}`;

  try {
    const response = await fetch(endpoint, {
      headers: { 'Authorization': `Bearer ${sid}` }
    });
    if (!response.ok) throw new Error(`SOQL query failed: ${response.statusText}`);
    const result = await response.json();
    return result.records[0]; // Return the matching record
  } catch (error) {
    console.error('Error fetching record details:', error);
    return null;
  }
}

Key Tips for Reliability

  • API Version Lock: Stick to a stable API version to avoid breaking changes when Salesforce updates their platform.
  • Permission Inheritance: Your plugin will only access objects/records that the logged-in user has permission to view—no extra setup needed.
  • UI Independence: Unlike DOM scraping, this method won't break if Salesforce tweaks their Lightning layout or adds new UI elements.

Putting it all together, you can initialize your plugin like this:

async function initPlugin() {
  const objectApiName = getCurrentSObjectApiName();
  if (!objectApiName) {
    console.log('No Salesforce object detected on this page');
    return;
  }

  // Fetch object metadata
  const objectDetails = await getSObjectDetails(objectApiName);
  console.log('Current object metadata:', objectDetails);

  // If on a record page, fetch record details
  const recordId = getCurrentRecordId(); // Implement this similar to getCurrentSObjectApiName
  if (recordId) {
    const recordDetails = await getRecordDetails(objectApiName, recordId);
    console.log('Current record details:', recordDetails);
  }
}

initPlugin();

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 07:26:24