Skip to content

Commit

Permalink
Add example for saving variable across domain visits (cypress-io#2658)
Browse files Browse the repository at this point in the history
  • Loading branch information
jennifer-shehane authored Mar 25, 2020
1 parent 395dbb2 commit ad7e244
Showing 1 changed file with 45 additions and 1 deletion.
46 changes: 45 additions & 1 deletion source/api/commands/task.md
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,7 @@ Option | Default | Description

# Examples

## Command
## Event

`cy.task()` provides an escape hatch for running arbitrary Node code, so you can take actions necessary for your tests outside of the scope of Cypress. This is great for:

Expand Down Expand Up @@ -176,6 +176,50 @@ module.exports = (on, config) => {
}
```

### Save a variable across non same-origin URL visits

When visiting non same-origin URL, Cypress will {% url "change the hosted URL to the new URL" web-security %}, wiping the state of any local variables. We want to save a variable across visiting non same-origin URLs.

We can save the variable and retrieve the saved variable outside of the test using `cy.task()` as shown below.

```javascript
// in test
describe('Href visit', () => {
it('captures href', () => {
cy.visit('https://www.mywebapp.com')
cy.get('a').invoke('attr', 'href')
.then((href) => {
// href is not same-origin as current url
// like https://www.anotherwebapp.com
cy.task('setHref', href)
})
})

it('visit href', () => {
cy.task('getHref').then((href) => {
// visit non same-origin url https://www.anotherwebapp.com
cy.visit(href)
})
})
})
```

```javascript
// in plugins/index.js
let href

module.exports = (on, config) => {
on('task', {
setHref: (val) => {
return href = val
},
getHref: () => {
return href
}
})
}
```

## Options

### Change the timeout
Expand Down

0 comments on commit ad7e244

Please sign in to comment.