2
0

(logic) Add execute in parent window context for code block

This commit is contained in:
Baptiste Arnaud
2022-11-09 15:08:42 +01:00
parent de0158be24
commit b31b603cc7
18 changed files with 91 additions and 56 deletions

View File

@@ -45,7 +45,8 @@
"react-dom": "18.2.0",
"tailwindcss": "3.2.1",
"typescript": "4.8.4",
"utils": "workspace:*"
"utils": "workspace:*",
"typebot-js": "workspace:*"
},
"peerDependencies": {
"db": "workspace:*",

View File

@@ -8,6 +8,7 @@ import React, {
useEffect,
useState,
} from 'react'
import { sendEventToParent } from 'services/chat'
import { safeStringify } from 'services/variable'
export type LinkedTypebot = Pick<
@@ -75,6 +76,15 @@ export const TypebotContext = ({
const updateVariableValue = (variableId: string, value: unknown) => {
const formattedValue = safeStringify(value)
sendEventToParent({
newVariableValue: {
name:
typebot.variables.find((variable) => variable.id === variableId)
?.name ?? '',
value: formattedValue ?? '',
},
})
setLocalTypebot((typebot) => ({
...typebot,
variables: typebot.variables.map((v) =>

View File

@@ -7,6 +7,7 @@ import {
TypingEmulation,
} from 'models'
import { isBubbleBlock, isInputBlock } from 'utils'
import type { TypebotPostMessageData } from 'typebot-js'
export const computeTypingTimeout = (
bubbleContent: string,
@@ -31,3 +32,17 @@ export const getLastChatBlockType = (
) as (BubbleBlock | InputBlock)[]
return displayedBlocks.pop()?.type
}
export const sendEventToParent = (data: TypebotPostMessageData) => {
try {
window.top?.postMessage(
{
from: 'typebot',
...data,
},
'*'
)
} catch (error) {
console.error(error)
}
}

View File

@@ -19,7 +19,8 @@ import {
VariableWithUnknowValue,
} from 'models'
import { byId, isDefined, isNotDefined, sendRequest } from 'utils'
import { sanitizeUrl } from './utils'
import { sendEventToParent } from './chat'
import { isEmbedded, sanitizeUrl } from './utils'
import { parseCorrectValueType, parseVariables } from './variable'
type EdgeId = string
@@ -153,14 +154,7 @@ const executeRedirect = (
try {
window.open(formattedUrl)
} catch (err) {
//Can't access to parent window
window.top?.postMessage(
{
from: 'typebot',
redirectUrl: formattedUrl,
},
'*'
)
sendEventToParent({ redirectUrl: formattedUrl })
}
} else {
window.open(formattedUrl, block.options.isNewTab ? '_blank' : '_self')
@@ -173,15 +167,25 @@ const executeCode = async (
{ typebot: { variables } }: LogicContext
) => {
if (!block.options.content) return
const func = Function(
...variables.map((v) => v.id),
parseVariables(variables, { fieldToParse: 'id' })(block.options.content)
)
try {
await func(...variables.map((v) => parseCorrectValueType(v.value)))
} catch (err) {
console.error(err)
console.log('isEmbedded', isEmbedded)
if (block.options.shouldExecuteInParentContext && isEmbedded) {
const func = Function(
...variables.map((v) => v.id),
parseVariables(variables)(block.options.content)
)
sendEventToParent({ codeToExecute: func })
} else {
const func = Function(
...variables.map((v) => v.id),
parseVariables(variables, { fieldToParse: 'id' })(block.options.content)
)
try {
await func(...variables.map((v) => parseCorrectValueType(v.value)))
} catch (err) {
console.error(err)
}
}
return block.outgoingEdgeId
}

View File

@@ -9,3 +9,8 @@ export const sanitizeUrl = (url: string): string =>
export const isMobile =
typeof window !== 'undefined' &&
window.matchMedia('only screen and (max-width: 760px)').matches
export const isEmbedded =
typeof window !== 'undefined' &&
window.parent &&
window.location !== window.top?.location

View File

@@ -4,6 +4,7 @@ import { LogicBlockType, blockBaseSchema } from '../shared'
export const codeOptionsSchema = z.object({
name: z.string(),
content: z.string().optional(),
shouldExecuteInParentContext: z.boolean().optional(),
})
export const codeBlockSchema = blockBaseSchema.and(

View File

@@ -1,6 +1,6 @@
{
"name": "typebot-js",
"version": "2.2.9",
"version": "2.2.10",
"main": "dist/index.js",
"unpkg": "dist/index.umd.min.js",
"license": "AGPL-3.0-or-later",

View File

@@ -1,4 +1,4 @@
import { DataFromTypebot, IframeCallbacks, IframeParams } from '../types'
import { TypebotPostMessageData, IframeCallbacks, IframeParams } from '../types'
import './style.css'
export const createIframe = ({
@@ -24,8 +24,8 @@ export const createIframe = ({
iframe.setAttribute('id', uniqueId)
if (backgroundColor) iframe.style.backgroundColor = backgroundColor
iframe.classList.add('typebot-iframe')
const { onNewVariableValue, onVideoPlayed } = iframeParams
listenForTypebotMessages({ onNewVariableValue, onVideoPlayed })
const { onNewVariableValue } = iframeParams
listenForTypebotMessages({ onNewVariableValue })
return iframe
}
@@ -50,14 +50,17 @@ const parseStarterVariables = (starterVariables?: {
export const listenForTypebotMessages = (callbacks: IframeCallbacks) => {
window.addEventListener('message', (event) => {
const data = event.data as { from?: 'typebot' } & DataFromTypebot
const data = event.data as { from?: 'typebot' } & TypebotPostMessageData
if (data.from === 'typebot') processMessage(event.data, callbacks)
})
}
const processMessage = (data: DataFromTypebot, callbacks: IframeCallbacks) => {
const processMessage = (
data: TypebotPostMessageData,
callbacks: IframeCallbacks
) => {
if (data.redirectUrl) window.open(data.redirectUrl)
if (data.newVariableValue && callbacks.onNewVariableValue)
callbacks.onNewVariableValue(data.newVariableValue)
if (data.videoPlayed && callbacks.onVideoPlayed) callbacks.onVideoPlayed()
if (data.codeToExecute) data.codeToExecute()
}

View File

@@ -8,7 +8,6 @@ export type IframeParams = {
export type IframeCallbacks = {
onNewVariableValue?: (v: Variable) => void
onVideoPlayed?: () => void
}
export type PopupParams = {
@@ -52,10 +51,10 @@ export type Variable = {
value: string
}
export type DataFromTypebot = {
export type TypebotPostMessageData = {
redirectUrl?: string
newVariableValue?: Variable
videoPlayed?: boolean
codeToExecute?: Function
}
export const localStorageKeys = {

View File

@@ -88,26 +88,6 @@ describe('createIframe', () => {
expect(v).toBe('varValue')
})
it('should notify when video played', async () => {
expect.assertions(1)
let hit = false
createIframe({
url: 'https://typebot.io/typebot-id',
onVideoPlayed: () => {
hit = true
},
})
window.postMessage(
{
from: 'typebot',
videoPlayed: true,
},
'*'
)
await new Promise((r) => setTimeout(r, 1))
expect(hit).toBe(true)
})
it("shouldn't execute callbacks if event from other than typebot", async () => {
expect.assertions(3)
let n, v