
本文介绍如何通过解析 URL 参数(如 mobilesize=1)动态设置 Google IMA SDK 的广告插槽尺寸,确保视频广告在移动设备上自适应显示,避免水平滚动和布局溢出问题。
本文介绍如何通过解析 url 参数(如 `mobilesize=1`)动态设置 google ima sdk 的广告插槽尺寸,确保视频广告在移动设备上自适应显示,避免水平滚动和布局溢出问题。
在使用 Google IMA SDK 集成视频广告时,linearAdSlotWidth 和 linearAdSlotHeight 等参数不仅影响广告请求的创意匹配逻辑,还直接决定 SDK 选择何种分辨率、宽高比的广告素材。若仅修改宽度(如从 640px 降为 401px)而忽略高度,将破坏原始宽高比(如常见的 4:3 或 16:9),导致广告被拉伸、裁剪,甚至因尺寸不匹配而无法正确渲染。
正确的做法是同步调整宽高,并严格保持原有比例。例如,桌面端默认采用 640×480(4:3),则移动端缩放至宽度 401px 时,对应高度应为 401 × (480/640) ≈ 301;同理,非线性广告(640×240,即 8:3)缩放后高度应为 401 × (240/640) ≈ 151。
以下是推荐的实现方式(含健壮性增强):
function getUrlParam(name) {
const urlParams = new URLSearchParams(window.location.search);
return urlParams.get(name) || '';
}
const adsRequest = new google.ima.AdsRequest();
adsRequest.adTagUrl = 'YOUR_AD_TAG_URL';
// 定义基础尺寸(桌面端)
let linearWidth = 640;
let linearHeight = 480;
let nonLinearWidth = 640;
let nonLinearHeight = 240;
// 检查 mobilesize=1 参数,动态切换尺寸
if (getUrlParam('mobilesize') === '1') {
linearWidth = 401;
linearHeight = Math.round((linearWidth * 480) / 640); // 401 × 0.75 = 300.75 → 301
nonLinearWidth = 401;
nonLinearHeight = Math.round((nonLinearWidth * 240) / 640); // 401 × 0.375 = 150.375 → 150
}
// 应用到 AdsRequest 实例
adsRequest.linearAdSlotWidth = linearWidth;
adsRequest.linearAdSlotHeight = linearHeight;
adsRequest.nonLinearAdSlotWidth = nonLinearWidth;
adsRequest.nonLinearAdSlotHeight = nonLinearHeight;
⚠️ 注意事项:
- IMA SDK 不会自动缩放广告容器,它仅依据你提供的插槽尺寸向广告服务器请求匹配素材。因此,前端还需确保
- 建议配合 CSS 媒体查询或 @media (max-width: 480px) 进行双重保障,尤其当用户未携带 mobilesize=1 参数但实际访问设备为手机时;
- 若需更智能的设备检测(而非依赖 URL 参数),可结合 navigator.userAgent 或 window.innerWidth 判断,但注意服务端 SSR 场景下需谨慎处理;
- 所有尺寸单位均为像素(px),且必须为整数,小数会被截断,故推荐使用 Math.round() 确保精度。
通过上述方式,既能精准控制广告请求的尺寸策略,又能保障视觉一致性与用户体验,真正实现“一处配置、多端适配”的广告集成目标。











