• /
  • EnglishEspañolFrançais日本語한국어Português
  • EntrarComeçar agora

Esta tradução de máquina é fornecida para sua comodidade.

Caso haja alguma divergência entre a versão em inglês e a traduzida, a versão em inglês prevalece. Acesse esta página para mais informações.

Criar um problema

interação (API SPA)

Sintaxe

newrelic.interaction([JSON object $options])

Retorna um novo objeto de identificador que está vinculado à interação SPA atual ou uma nova interação, caso não exista uma.

Requisitos

  • The .interaction() API requires Browser Pro+SPA agent (v963 or higher).
  • Supplying an $options object to the API is only supported in versions v1.285.0 and higher.
  • The waitForEnd option is only supported in v1.285.0 and higher.
  • The targetPageLoad option is only supported in v1.315.0 and higher.

Se você estiver instalando o agente do browser via npm e criando um agente personalizado com recursos selecionados, você deve habilitar o recurso spa ao criar a instância Agent. No array features, adicione o seguinte:

import { Agent } from '@newrelic/browser-agent/loaders/agent'
import { Spa } from '@newrelic/browser-agent/features/spa';
const options = {
info: { ... },
loader_config: { ... },
init: { ... },
features: [
... other features ...
Spa
]
}
new Agent(options)

Para obter mais informações, consulte a documentação de instalação do browser npm.

Descrição

The SPA monitoring interaction() API call allows you to control and customize SPA interactions tracked by the browser agent. Use this API to:

  • Manually create custom interactions for patterns that the browser agent doesn't automatically detect.
  • Modify existing interactions by adding custom attributes, naming them, or controlling when they complete.

Como funciona

When you call newrelic.interaction(), you get a handle (a JavaScript object) that references a BrowserInteraction event. This handle lets you call methods like .save(), .ignore(), .setName(), and .setAttribute() to control the interaction.

API behavior by interaction state

The API behaves differently depending on the current state of the interaction:

Estado

Comportamento

No interaction in progress

Creates a new custom interaction.

  • The custom interaction automatically closes when the next soft navigation completes (following default SPA heuristics), unless you set waitForEnd: true.
  • Use this to track user actions that don't trigger route changes, such as opening a modal or expanding a section.

Interaction already in progress

Returns a new handle that references the currently active interaction.

  • You can create multiple handles for the same interaction. This is useful when you want to control different aspects of an interaction from different parts of your code.
  • The existing interaction continues—this API can't replace or overwrite an interaction that's already in progress.
  • Works for both user-triggered interactions (like clicks) and API-triggered custom interactions.

Targeting the initial page load

When you use the targetPageLoad: true option, the handle always references the initial page load BrowserInteraction event.

  • This is the only way to access and modify the initial page load interaction.
  • Prior to this option, the initial page load wasn't accessible through the API.

Principais comportamentos

Comportamento

Descrição

Multiple handles are independent

Each call to newrelic.interaction() creates a separate handle object, even when referencing the same underlying interaction. Methods called on one handle don't affect other handles, but they all modify the same BrowserInteraction event.

Can't overwrite interactions

If a user clicks a button (starting an interaction) and your code then calls newrelic.interaction(), the API returns a handle to the click interaction—it doesn't create a new one. The browser agent prioritizes real user interactions.

Handles become inactive

Once an interaction completes, any handles referencing it become inactive. Method calls on inactive handles have no effect and don't throw errors.

Use waitForEnd for precise control

By default, interactions close based on SPA heuristics (route changes, AJAX completion, DOM settling). Setting waitForEnd: true keeps the interaction open until you explicitly call .end() on the handle.

Cuidado

Using waitForEnd: true together with targetPageLoad: true will keep the initial page load BrowserInteraction event open indefinitely until .end() is called, changing the default definition of the initial page load BrowserInteraction event. This is an advanced use case and should be used with caution.

Parâmetro

Parâmetro

Descrição

$options

Objeto JSON

Opcional: especifica opções que afetam o comportamento da interação.

  • waitForEnd - (v1.285.0+) Default is false. To forcibly keep the interaction open until the .end method is called on its handle, set it to true. After an interaction is earmarked with this, it cannot be undone.
  • targetPageLoad - (v1.315.0+) Default is false. If set to true, the returned handle is bound to the initial page load interaction instead of creating or targeting a soft navigation interaction. This is the only way to target the initialPageLoad interaction.

Valores de retorno

Este método retorna um objeto JS nativo que aponta para um eventoBrowserInteraction potencial. Cada vez que esse método é chamado para o mesmo BrowserInteraction enquanto ele ainda não terminou, um novo objeto é criado, mas ele ainda faz referência à mesma interação.

Exemplos

SPA API methods can be applied to the returned output of newrelic.interaction(). You can assign the returned value or handle to another variable for later use. For example:

let myInteraction = newrelic.interaction();
...
myInteraction.save();

For a list of interaction APIs, see Track single page apps.

Embora o identificador nomeado possa ser salvo e usado de fora de uma interação, observe que os métodos SPA não terão efeito após o término da interação.

A duração da interação também pode ser personalizada usando o seguinte método:

// Say an interaction is already open from a user click.
const userInteraction = newrelic.interaction({ waitForEnd: true }); // grabs the current interaction in-progress & keep it open
// URL changes & DOM is modified. Because of those condition being met, interaction will be saved but is kept open.
fetch('myurl.com/endpoint').then(() => userInteraction.end()) // associate this request to the interaction before completing this BrowserInteraction
const myCustomIxn = newrelic.interaction({ waitForEnd: true }) // create a new api-triggered interaction
// This interaction will be kept open indefinitely until `.end` is called, and no new interaction will start, custom or otherwise. AjaxRequest will continue to buffer under this interaction until it is closed.
Copyright © 2026 New Relic Inc.

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.