簡體   English   中英

通過WebDriver在C#中執行Javascript文件

[英]Execute Javascript file in C# through WebDriver

我正在嘗試通過 C# 中的 webdriver 執行一個 javascript 文件。 以下是我到目前為止所擁有的:

IJavaScriptExecutor js = driver as IJavaScriptExecutor;
(string)js.ExecuteScript("var s = window.document.createElement(\'script\'); s.src = \'E:\\workspace\\test\\jsPopup.js\'; window.document.head.appendChild(s); ");
js.ExecuteScript("return ourFunction");

jsfile.js 的內容是

 document.ourFunction =  function(){ tabUrl = window.location.href;
 imagesPath = chrome.extension.getURL("images"); 
 var optionsPopupPath = chrome.extension.getURL("options.html");
 }

但是當我執行

js.ExecuteScript("return ourFunction");

它拋出了一個未找到 ourFunction 的異常。 我想要做的是通過 js 注入或任何其他方法運行一個完整的 javascript 文件,它可以讓我訪問由 js 文件生成的數據。 有什么幫助嗎?

這里存在三個問題:

  1. 正如@Crowcoder 指出的,你需要ourFunction() ,而不是ourFunction ,否則你會得到一個Uncaught ReferenceError: ourFunction is not defined(…)
  2. 接下來, ourFunction被添加到document而不是全局范圍,所以你需要document.ourFunction() ,否則你會得到同樣的錯誤。
  3. 最后,該函數不返回任何內容,因此執行它會返回undefined 如果您嘗試返回它的“值”,您將在瀏覽器中得到類似Uncaught SyntaxError: Illegal return statement(…)的信息,或者在您的代碼中返回null

您可以從瀏覽器控制台測試所有這些,而無需啟動 WebDriver。

如果您將方法更改為:

document.ourFunction = function(){ tabUrl = window.location.href;
  imagesPath = chrome.extension.getURL("images"); 
  var optionsPopupPath = chrome.extension.getURL("options.html");
  return optionsPopupPath;  // return here!
}

然后js.ExecuteScript("return document.ourFunction()"); 應該工作。

更新:

(您可以嘗試: js.ExecuteScript("return document.ourFunction();"); (添加分號)但這應該沒什么區別。)

我建議(除了添加return語句)臨時注釋掉chrome.extension行,以防它們拋出錯誤並導致函數無法創建。 我認為這是迄今為止失敗的最可能的來源。

這樣做后,這對我來說在 Firefox 和 Chrome 中很好用,根本沒有任何顯式或隱式等待。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM