adList.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386
  1. /**
  2. * 创建广告
  3. * config 参数说明
  4. * @param {string[]} ad_id 广告id
  5. * @param {string} ad_type 广告类型 1:视频 2:图片
  6. * @param {string} ad_pos 广告位置
  7. * @param {string[]} ad_size 广告尺寸
  8. * @param {string} ad_text 广告文案
  9. * @param {string[]} ad_url 广告链接
  10. * @param {string[]} ad_cover 广告图片
  11. */
  12. document.addEventListener('DOMContentLoaded', function () {
  13. const agreement =
  14. location.origin === 'http://' ? 'http:' : location.origin === 'https://' ? 'https:' : 'http://'
  15. const base = agreement + '10.30.160.129:8082/'
  16. /**
  17. * 广告初始化
  18. * @param config 广告配置
  19. * @returns
  20. */
  21. function ad_init(config = {}) {
  22. // 启动上报
  23. const slots = config.slots || []
  24. const D = new Date()
  25. const dateTime = D.getTime()
  26. for (let i = 0; i < slots.length; i++) {
  27. const v = slots[i]
  28. if (!v.creativesList || !v.creativesList.length) continue
  29. // 获取对应广告位置
  30. const ad_pos = document.querySelector('#sxtv-ad-' + v.slotId)
  31. if (!ad_pos) {
  32. console.error('广告位置不存在:#sxtv-ad-' + v.slotId)
  33. continue
  34. }
  35. const gg = document.createElement('div')
  36. gg.innerHTML =
  37. '<svg t="1734493782806" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="9775" width="32" height="32"><path d="M560.88 658.8h69.68v15.44h-69.68z" p-id="9776" fill="#515151"></path><path d="M698.24 451.44V200h-46.56v251.44H372.32V200h-46.56v251.44H186V824h651.92V451.44zM505.12 600H396.16v90.72L352 700.08v-33.92l8-2.4V575.2h54.24l-1.84-8.8h45.84l1.68 8.8h44.88z m162.72 96.48H524.4v-60h143.44z m5.36-64.48H518.88v-23.36h61.12v-11.28h-22.16l-2.88 8.48H520V582.4h8.72l5.52-13.76H568l-2.32 6.64h14.32v-8h38.64v8h49.04v22h-49.04v11.36h54.56z" p-id="9777" fill="#515151"></path></svg>'
  38. gg.style.position = 'absolute'
  39. gg.style.top = 0
  40. gg.style.right = 3
  41. gg.style.zIndex = 999999
  42. // 判定当前时间是否在creativesList的时间内
  43. const ele = document.createElement('div')
  44. ele.style.position = 'relative'
  45. ele.appendChild(gg)
  46. for (let o = 0; o < v.creativesList.length; o++) {
  47. const item = v.creativesList[o]
  48. const start = new Date(item.startDate + ' 00:00:00').getTime()
  49. const end = new Date(item.endDate + ' 23:59:59').getTime()
  50. // 判断变量是否数组
  51. if (dateTime < start || dateTime > end || !Array.isArray(item.stuffsList)) continue
  52. // 获取广告类型 1 轮播 2 交替 3 单项
  53. const showType = item.showType
  54. let e =
  55. showType === 1
  56. ? generateCarouselAd(item, D, v.slotId, v.width || 0, v.height || 0)
  57. : generateAlternateAd(item, D, v.slotId, v.width || 0, v.height || 0)
  58. if (e == -1) break
  59. ele.appendChild(e)
  60. ele.style.width = '100%'
  61. ele.style.height = '100%'
  62. }
  63. ad_pos.style.width = (v.width || 0) + 'px'
  64. ad_pos.style.height = (v.height || 0) + 'px'
  65. ad_pos.style.border = 'none'
  66. ad_pos.style.overflow = 'hidden'
  67. ad_pos.appendChild(ele)
  68. }
  69. }
  70. // 生成轮播广告
  71. const generateCarouselAd = function (generateCarousel = {}, D, slotId, width, height) {
  72. const week = D.getDay() === 0 ? 6 : D.getDay() - 1
  73. const timeInterval = (generateCarousel.timeInterval || '')
  74. .slice(week * 24, week * 24 + 24)
  75. .split('')
  76. const H = D.getHours()
  77. if (generateCarousel.intervalType === 2 && timeInterval[H] == 0) return -1
  78. const T = (generateCarousel.showIntervalTime || 5) * 1000
  79. return createCarousel(generateCarousel.stuffsList, T, slotId, width, height)
  80. }
  81. // 生成交替广告
  82. const generateAlternateAd = function (generateAlternate = {}, D, slotId, width, height) {
  83. const week = D.getDay() === 0 ? 6 : D.getDay() - 1
  84. const timeInterval = (generateAlternate.timeInterval || '')
  85. .slice(week * 24, week * 24 + 24)
  86. .split('')
  87. const H = D.getHours()
  88. if (generateAlternate.intervalType === 2 && timeInterval[H] == 0) return -1
  89. const stuff =
  90. generateAlternate.stuffsList[
  91. Math.floor((H * 60 + D.getMinutes()) / (generateAlternate.showIntervalTime || 5)) %
  92. generateAlternate.stuffsList.length
  93. ]
  94. if (!stuff) return -1
  95. const fileType = stuff.addr.split('.').pop()
  96. // fileType是否是图片类型
  97. if (fileType === 'jpg' || fileType === 'png' || fileType === 'gif') {
  98. const son_ele = document.createElement('img')
  99. son_ele.src = stuff.addr
  100. son_ele.style.width = width + 'px'
  101. son_ele.style.height = height + 'px'
  102. son_ele.onload = () => {
  103. const uuid = localStorage.getItem('ad_id')
  104. fetch(`${base}ad/show?uuid=${uuid}&stuffId=${stuff.stuffId}&slotId=${slotId}`).then((res) =>
  105. res.text(),
  106. )
  107. }
  108. son_ele.addEventListener('click', () => {
  109. const uuid = localStorage.getItem('ad_id')
  110. // 点击广告
  111. fetch(`${base}ad/click?uuid=${uuid}&stuffId=${stuff.stuffId}&slotId=${slotId}`)
  112. .then((res) => res.text())
  113. .then(() => {
  114. window.open(stuff.landingPage)
  115. })
  116. })
  117. return son_ele
  118. }
  119. const son_ele = document.createElement('video')
  120. son_ele.setAttribute('loop', 'loop')
  121. son_ele.setAttribute('autoplay', 'autoplay')
  122. son_ele.setAttribute('muted', 'muted')
  123. son_ele.src = stuff.addr
  124. son_ele.style.width = '100%'
  125. son_ele.style.height = '100%'
  126. // 视频加载允许播放的回调
  127. son_ele.oncanplay = () => {
  128. son_ele.play()
  129. const uuid = localStorage.getItem('ad_id')
  130. fetch(`${base}ad/show?uuid=${uuid}&stuffId=${src.stuffId}&slotId=${slotId}`).then((res) =>
  131. res.text(),
  132. )
  133. }
  134. son_ele.addEventListener('click', () => {
  135. const uuid = localStorage.getItem('ad_id')
  136. // 点击广告
  137. fetch(`${base}ad/click?uuid=${uuid}&stuffId=${stuff.stuffId}&slotId=${slotId}`)
  138. .then((res) => res.text())
  139. .then(() => {
  140. window.open(stuff.landingPage)
  141. })
  142. })
  143. // 对body添加一次性点击事件
  144. const play = () => {
  145. son_ele.play()
  146. // 移除点击
  147. document.body.removeEventListener('click', play)
  148. }
  149. document.body.addEventListener('click', play)
  150. return son_ele
  151. }
  152. function generateBrowserFingerprint() {
  153. return new Promise((resolve, reject) => {
  154. // 在这里执行获取指纹的操作,例如使用Canvas、WebGL等方法
  155. // 然后将生成的指纹字符串作为参数传递给resolve函数
  156. // 获取浏览器信息
  157. const browserInfo = `${navigator.userAgent} ${window.screen.width}x${window.screen.height}`
  158. // 获取时区偏移量
  159. const timezoneOffset = Intl.DateTimeFormat().resolvedOptions().timeZone
  160. // 在这里处理获取到的指纹信息
  161. const canvasFingerprint = getCanvasFingerprint()
  162. const webglFingerprint = getWebglFingerprint()
  163. // 将所有信息组合成一个字符串
  164. const fingerprintStr = `${browserInfo}|${timezoneOffset}|${canvasFingerprint}|${webglFingerprint}`
  165. // 使用createHash生成哈希值
  166. createHash(fingerprintStr)
  167. .then((hash) => {
  168. resolve(hash)
  169. })
  170. .catch((error) => {
  171. reject(error)
  172. })
  173. })
  174. }
  175. // Canvas指纹获取函数
  176. function getCanvasFingerprint() {
  177. const canvas = document.createElement('canvas')
  178. const ctx = canvas.getContext('2d')
  179. if (!ctx) return ''
  180. // 绘制一些内容
  181. ctx.fillStyle = '#f60'
  182. ctx.fillRect(0, 0, 16, 16)
  183. ctx.fillStyle = '#069'
  184. ctx.font = '11pt Arial'
  185. ctx.fillText('Cwm fjord!!', 4, 10)
  186. ctx.fillStyle = 'rgba(102, 204, 0, 0.7)'
  187. ctx.fillText('Cwm fjord!!', 5, 11)
  188. ctx.scale(2, 2)
  189. ctx.fillStyle = '#fff'
  190. ctx.font = '24pt Arial'
  191. ctx.fillText('Cwm fjord!!', 10, 25)
  192. ctx.fillStyle = 'rgba(102, 204, 0, 0.7)'
  193. ctx.fillText('Cwm fjord!!', 10, 25)
  194. const data = canvas.toDataURL()
  195. return data.replace(/data:image\/png;base64,/, '')
  196. }
  197. // WebGL指纹获取函数
  198. function getWebglFingerprint() {
  199. const canvas = document.createElement('canvas')
  200. const gl = canvas.getContext('webgl') || canvas.getContext('experimental-webgl')
  201. if (!gl) return ''
  202. const extensions = gl.getSupportedExtensions()
  203. if (!extensions) return ''
  204. const extStr = extensions.join(',')
  205. const rendererInfo = gl.getParameter(gl.RENDERER) + '/' + gl.getParameter(gl.VENDOR)
  206. return rendererInfo + extStr
  207. }
  208. function createHash(str) {
  209. if (!crypto || !crypto.subtle || !crypto.subtle.digest || !TextEncoder) {
  210. console.error('浏览器不支持创建哈希值')
  211. return Promise.reject()
  212. }
  213. // 将字符串转换为 Uint8Array
  214. const encoder = new TextEncoder()
  215. const data = encoder.encode(str)
  216. // 使用 SubtleCrypto API 计算 SHA-256 摘要
  217. return new Promise((resolve, reject) => {
  218. crypto.subtle
  219. .digest('SHA-256', data)
  220. .then((hashBuffer) => {
  221. // 将 ArrayBuffer 转换为十六进制字符串
  222. const hashArray = Array.from(new Uint8Array(hashBuffer))
  223. const hashHex = hashArray.map((byte) => byte.toString(16).padStart(2, '0')).join('')
  224. resolve(hashHex)
  225. })
  226. .catch((error) => {
  227. reject(error)
  228. })
  229. })
  230. }
  231. // 轮播
  232. function createCarousel(images, interval, slotId, width, height) {
  233. // 创建轮播图容器
  234. const carouselContainer = document.createElement('div')
  235. carouselContainer.style = `
  236. position: relative;
  237. width: 100%;
  238. height: 100%;
  239. margin: auto;
  240. overflow: hidden;
  241. `
  242. // 创建图片容器
  243. const imagesContainer = document.createElement('div')
  244. imagesContainer.style = `
  245. width: ${images.length * width}px;
  246. height: ${height}px;
  247. display: flex;
  248. transition: transform 0.5s ease;
  249. `
  250. // 创建指示器容器
  251. const indicatorsContainer = document.createElement('div')
  252. indicatorsContainer.style = `
  253. position: absolute;
  254. bottom: 10px;
  255. left: 50%;
  256. margin-right: 5px;
  257. transform: translateX(-50%);
  258. `
  259. // 添加图片到容器
  260. images.forEach((src, index) => {
  261. const img = document.createElement('img')
  262. img.src = src.addr
  263. img.alt = `Image ${index + 1}`
  264. img.style = `
  265. flex: 1;
  266. width: ${width}px;
  267. height: 100%;
  268. `
  269. img.addEventListener('click', () => {
  270. const uuid = localStorage.getItem('ad_id')
  271. // 点击广告
  272. fetch(`${base}ad/click?uuid=${uuid}&stuffId=${src.stuffId}&slotId=${slotId}`)
  273. .then((res) => res.text())
  274. .then(() => {
  275. window.open(src.landingPage)
  276. })
  277. })
  278. // 图片加载完成
  279. img.onload = () => {
  280. const uuid = localStorage.getItem('ad_id')
  281. fetch(`${base}ad/show?uuid=${uuid}&stuffId=${src.stuffId}&slotId=${slotId}`).then((res) =>
  282. res.text(),
  283. )
  284. }
  285. imagesContainer.appendChild(img)
  286. // 添加指示器
  287. const indicator = document.createElement('button')
  288. indicator.style = `
  289. border: none;
  290. background-color: #fff;
  291. cursor: pointer;
  292. padding: 5px;
  293. border-radius: 50%;
  294. width: 10px;
  295. height: 10px;
  296. margin-right: 5px;
  297. display: inline-block;
  298. `
  299. if (index !== 0) indicator.style.backgroundColor = '#ccc'
  300. indicator.dataset.target = index
  301. indicatorsContainer.appendChild(indicator)
  302. })
  303. // 将图片容器和指示器容器添加到轮播图容器
  304. carouselContainer.appendChild(imagesContainer)
  305. carouselContainer.appendChild(indicatorsContainer)
  306. // 设置轮播图的切换逻辑
  307. let currentImageIndex = 0
  308. const maxImages = images.length
  309. function showImage(index) {
  310. // 更新图片位置
  311. imagesContainer.style.transform = `translateX(-${index * width}px)`
  312. // 更新指示器
  313. indicatorsContainer.querySelectorAll('button').forEach((btn, i) => {
  314. btn.style.backgroundColor = i === index ? '#000' : '#ccc'
  315. })
  316. currentImageIndex = index
  317. }
  318. function nextImage() {
  319. currentImageIndex = (currentImageIndex + 1) % maxImages
  320. showImage(currentImageIndex)
  321. }
  322. // 为指示器添加点击事件
  323. indicatorsContainer.addEventListener('click', function (e) {
  324. if (e.target.tagName === 'BUTTON') {
  325. const targetIndex = parseInt(e.target.dataset.target)
  326. showImage(targetIndex)
  327. }
  328. })
  329. // 自动播放轮播图
  330. let intervalId = setInterval(nextImage, interval)
  331. // 可选:鼠标悬停时停止自动播放
  332. carouselContainer.addEventListener('mouseenter', () => {
  333. clearInterval(intervalId)
  334. })
  335. carouselContainer.addEventListener('mouseleave', () => {
  336. intervalId = setInterval(nextImage, interval)
  337. })
  338. return carouselContainer
  339. }
  340. // 轮播End
  341. const script = document.querySelector('#sxtv-ad-id')
  342. const CFG = agreement + 'cxzx.smcic.net/ad/catalog/' + script.getAttribute('ad_id') + '.json'
  343. try {
  344. fetch(CFG + '?' + Date.now())
  345. .then((res) => res.json())
  346. .then((res) => {
  347. const data = res
  348. // 广告sdk
  349. if (localStorage.getItem('ad_id')) {
  350. ad_init(data)
  351. return
  352. }
  353. // 生成并输出浏览器指纹
  354. generateBrowserFingerprint().then((ad_id) => {
  355. localStorage.setItem('ad_id', ad_id + '')
  356. ad_init(data)
  357. })
  358. })
  359. } catch (error) {
  360. console.error(error)
  361. }
  362. })