Skip to content

Instantly share code, notes, and snippets.

@ITJesse
Last active June 20, 2025 03:12
Show Gist options
  • Save ITJesse/1783273c11e95f7997d2323d69cbac40 to your computer and use it in GitHub Desktop.
Save ITJesse/1783273c11e95f7997d2323d69cbac40 to your computer and use it in GitHub Desktop.
DLsite Aff Ads
import React, { useEffect, useRef, useState } from 'react'
/**
* DLSite Blogparts 广告组件
* @param {object} props
* @param {string} [props.id] - 广告 id
*/
const DlsiteBlogparts = ({
id = '',
height = '250px',
}: {
id?: string
height?: string
}) => {
const iframeRef = useRef<HTMLIFrameElement>(null)
const containerRef = useRef<HTMLDivElement>(null)
const [isVisible, setIsVisible] = useState(false)
useEffect(() => {
const observer = new window.IntersectionObserver(
(entries) => {
if (entries[0].isIntersecting) {
setIsVisible(true)
observer.disconnect()
}
},
{ rootMargin: '200px' }, // 提前 200px 加载
)
if (containerRef.current) {
observer.observe(containerRef.current)
}
return () => observer.disconnect()
}, [])
useEffect(() => {
if (!isVisible) return
const iframe = iframeRef.current
if (!iframe) return
const doc = iframe.contentDocument || iframe.contentWindow?.document
if (!doc) return
const adHtml = `
<!DOCTYPE html>
<html>
<head>
<style>
html, body {
margin: 0;
padding: 0;
background: transparent;
color: black;
}
.DLsite_bp_body { margin: 0 !important; border-width: 0px !important; background: transparent !important; padding: 0 !important; }
.DLsite_bp_inner { margin: 0 32px !important; }
.DLsite_bp_btn_prev, .DLsite_bp_btn_next { width: 32px !important; }
@media (prefers-color-scheme: dark) {
.DLsite_bp_work_name a { color: #e2e8f0 !important; } /* gray-200 */
.DLsite_bp_circle_name a { color: #a0aec0 !important; } /* gray-400 */
}
</style>
</head>
<body>
<script type="text/javascript">blogparts={"id":"${id}","ssl":"1"};<\/script>
<script type="text/javascript" src="https://www.dlsite.com/js/blogparts.js"><\/script>
</body>
</html>
`
doc.open()
doc.write(adHtml)
doc.close()
}, [id, isVisible])
return (
<div className="w-full flex" ref={containerRef}>
<iframe
ref={iframeRef}
style={{
border: 'none',
colorScheme: undefined, // 跟随网页,不强制 dark
height: height,
}}
className="w-full bg-gray-100 rounded-md p-2 box-content"
scrolling="no"
allowTransparency={true}
/>
</div>
)
}
export default DlsiteBlogparts
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment