protected audience api 的竞价逻辑无法在 html 中直接实现,必须通过 https 页面中 javascript 调用 runadauction(),且依赖浏览器支持、interest group 注册、worklet 脚本及合法 auctionconfig 配置。

Protected Audience API 的竞价逻辑在 HTML 中无法直接实现
HTML 本身是静态标记语言,不提供执行竞价逻辑的能力。所谓“HTML 做 Protected Audience 竞价”,本质是误解——runAdAuction() 必须在支持 FLEDGE 的浏览器环境中,由 JavaScript 在 worklet(如 ad-auction.js)中调用,且依赖 registerAdBeacon()、reportWin() 等配套机制。
常见错误现象:ReferenceError: runAdAuction is not defined 或控制台提示 Ad auction failed: Not supported in this context,往往是因为在普通 HTML 的 <script></script> 标签里直接调用该函数,而未满足运行前提。
- 必须启用 Chrome(117+)或 Edge(117+)的实验性功能:
--enable-features=InterestGroupStorage,ProtectedAudienceAPI - 页面需通过 HTTPS(
localhost除外)加载,HTTP 下整个 API 被禁用 -
runAdAuction()只能在顶层文档的fetch()响应中触发,不能在内联脚本或非可信上下文中调用
如何在网页中正确触发 Protected Audience 竞价流程
核心不是“写 HTML”,而是构造合法的 JS 执行链路:先注册 interest group,再发起竞价请求。HTML 只负责承载和触发 JS。
典型结构如下:
<title>PA Demo</title><button id="start">Start Auction</button>
<script>
document.getElementById("start").onclick = async () => {
// 1. 注册 interest group(需同源、HTTPS)
await navigator.joinAdInterestGroup({
owner: "https://example.com",
name: "sports-fans",
biddingLogicURL: "https://example.com/bidding.js",
ads: [{ renderURL: "https://example.com/ad1.html" }]
});
// 2. 发起竞价(关键:必须在 fetch 响应体中调用)
const response = await fetch("/auction?trigger=win");
const auctionConfig = await response.json();
const result = await navigator.runAdAuction(auctionConfig); // ✅ 此处才真正触发
if (result) document.body.innerHTML = `<iframe src="${result}" width="100%" height="250">`;
};
</script>
-
auctionConfig必须包含decisionLogicURL和至少一个interestGroupBuyers数组项 -
biddingLogicURL和decisionLogicURL必须返回application/javascript且无 CORS 阻止头 - Chrome 控制台 → Application → Interest Groups 标签页可手动验证 group 是否注册成功
常见报错及绕过条件判断方法
很多开发者卡在 TypeError: Cannot read properties of undefined (reading 'runAdAuction') 或 NotSupportedError,不是代码写错,而是环境未就绪。
建议加一层运行时检测:
if (!("runAdAuction" in navigator)) {
console.warn("Protected Audience API not available");
return;
}
if (!document.featurePolicy?.features().includes("browsing-topics")) {
console.warn("Feature policy blocks PA usage");
return;
}
if (location.protocol !== "https:" && location.hostname !== "localhost") {
console.warn("Must be HTTPS (or localhost)");
return;
}
- 检查 Chrome 地址栏右上角是否显示「? 安全」图标,否则 API 全部静默失效
- 打开
chrome://flags/#interest-group-api确认状态为 Enabled - 若使用本地开发,
file://协议绝对不行,必须用python3 -m http.server 8000 --bind 127.0.0.1启 HTTP 服务并访问http://127.0.0.1:8000
为什么不能把竞价逻辑写进 HTML 的 script 标签里
因为 runAdAuction() 的执行依赖浏览器的隐私沙箱调度器,它只接受来自可信来源(如 decisionLogicURL 返回的 worklet 脚本)的竞价规则。直接在主文档 JS 中写 generateBid() 函数会被忽略。
真实竞价行为发生在独立 worklet 环境中,与页面主线程隔离。你写的 HTML + 主线程 JS,最多只能做三件事:
- 调用
navigator.joinAdInterestGroup()注册人群 - 构造并传入
auctionConfig对象 - 接收
runAdAuction()返回的blob:URL 并渲染
所有出价计算、胜出判定、归因上报,都必须下沉到服务器托管的 .js worklet 文件中——这部分根本不在 HTML 范畴内。
大量免费API接口:立即使用
涵盖生活服务API、金融科技API、企业工商API、等相关的API接口服务。免费API接口可安全、合规地连接上下游,为数据API应用能力赋能!











