انتقل إلى المحتوى الرئيسي

إضافة نص برمجي للتهيئة

يضيف نصًا برمجيًا سيتم تقييمه في أحد السيناريوهات التالية:

  • في كل مرة يتم فيها التنقل في الصفحة.
  • في كل مرة يتم فيها إرفاق الإطار الفرعي أو التنقل فيه. في هذه الحالة، يتم تقييم النص البرمجي في سياق الإطار المرفق حديثًا.

يتم تقييم النص البرمجي بعد إنشاء المستند ولكن قبل تشغيل أي من نصوصه البرمجية. لإزالة نص التهيئة البرمجي من الصفحة مرة أخرى، استدعِ الدالة التي تم إرجاعها بواسطة هذه الدالة.

هذا مفيد لتعديل بيئة JavaScript، على سبيل المثال لتعيين قيمة Math.random.

الاستخدام
browser.addInitScript(script, args)
المعاملات
الاسمالنوعالتفاصيل
scriptFunctionدالة لحقنها كنص برمجي للتهيئة
argsnumber, string, booleanمعاملات للنص البرمجي
أمثلة
addInitScript.js
const script = await browser.addInitScript((seed) => {
Math.random = () => seed
}, 42)

await browser.url('https://webdriver.io')
console.log(await browser.execute(() => Math.random())) // returns 42

await reset()
await browser.url('https://webdriver.io')
console.log(await browser.execute(() => Math.random())) // returns a random number

hermore you can also use the `emit` function to send data back to the Node.js environment.
is useful if you want to observe certain events in the browser environment, e.g.:

addInitScriptWithEmit.js
const script = await browser.addInitScript((emit) => {
const observer = new MutationObserver((mutations) => {
for (const mutation of mutations) {
emit(mutation.target.nodeName)
}
})
observer.observe(document, { childList: true, subtree: true })
})

script.on('data', (data) => {
console.log(data) // prints: BODY, DIV, P, ...
})

Welcome! How can I help?

WebdriverIO AI Copilot