如何使用JMeter捕获浏览器中短暂存在的Local Storage键值对?
问题描述
访问某URL时,浏览器会动态生成新的键值对并存入Local Storage,但页面随即重定向至认证页面,该键值对会在2秒内消失。当前使用JMeter的jp@gc WebDriver插件在Chrome中开展测试,无法在其消失前捕获到该键值对。
解决方法
1. 拦截页面重定向
直接阻止重定向,避免Local Storage被清空:
- 在JMeter的WebDriver Sampler配置中,添加Chrome启动参数:
--disable-redirects - 或通过Chrome DevTools协议精准拦截认证页面的重定向请求,Groovy脚本示例:
def devTools = driver.getDevTools() devTools.createSession() devTools.send(org.openqa.selenium.devtools.v118.network.Network.enable()) devTools.addListener(org.openqa.selenium.devtools.v118.network.Network.requestWillBeSent(), { req -> // 替换为认证页面的URL特征关键词 if (req.request.url.contains("auth")) { devTools.send(org.openqa.selenium.devtools.v118.network.Network.cancelRequest(req.requestId)) } }) // 访问目标URL driver.get("你的目标URL") // 读取Local Storage def targetValue = driver.executeScript("return localStorage.getItem('目标键名');") log.info("捕获到的键值对: " + targetValue)
2. 提前注入监听脚本捕获写入事件
在页面加载前注入JS,监听Local Storage的setItem操作,一旦目标键被写入立即保存:
// 注入监听脚本,替换为你的目标键名 driver.executeScript(""" window.capturedData = null; const originalSetItem = localStorage.setItem; localStorage.setItem = function(key, value) { if (key === '要捕获的键名') { window.capturedData = {key: key, value: value}; } originalSetItem.apply(this, arguments); }; """) // 访问目标URL driver.get("你的目标URL") // 立即读取捕获到的数据 def result = driver.executeScript("return window.capturedData;") log.info("捕获结果: " + result) vars.put("capturedKeyValue", result.toString()) // 存入JMeter变量供后续使用
3. 用显式等待轮询Local Storage
针对键值对的短暂存在时长,设置2秒内的显式等待,轮询直到目标键出现:
import org.openqa.selenium.support.ui.WebDriverWait import org.openqa.selenium.support.ui.ExpectedConditions def wait = new WebDriverWait(driver, 2) // 等待时长匹配键值对存在时间 try { // 替换为目标键名 wait.until({ d -> d.executeScript("return localStorage.getItem('目标键名');") != null }) def targetValue = driver.executeScript("return localStorage.getItem('目标键名');") log.info("成功捕获: " + targetValue) vars.put("capturedValue", targetValue) } catch (Exception e) { log.error("未捕获到目标键值对: " + e.getMessage()) }
4. 检查Chrome运行配置
确保Chrome未启用无痕模式或自动清除存储的设置,可指定固定用户目录避免临时配置:
def options = new org.openqa.selenium.chrome.ChromeOptions() // 替换为你的Chrome用户数据目录 options.addArguments("--user-data-dir=C:/Users/你的用户名/AppData/Local/Google/Chrome/User Data") driver = new org.openqa.selenium.chrome.ChromeDriver(options)
内容的提问来源于stack exchange,提问作者Krishnaveni
相关产品推荐
相关产品推荐

