Bypass Bilibili's anti-hotlink to fetch images - Vinking
Bypass Bilibili's anti-hotlink to fetch images
·(edited)· / , ·172172 reads·22 likes
This article was last modified on . Some content may be outdated. Feel free to ask the author if you have questions.
AI Translation中文English
Key Insights
AI · GEN
Bypass Bilibili's anti-hotlink to fetch images
Loading...
Loading...
Loading...
Loading...
Loading...
A long time ago I wrote an off-site link card for my website in JS, and recently added Bilibili link parsing. When writing an article you only need one line of code to turn a Bilibili link into a card automatically, e.g.:
[share url="https://www.bilibili.com/video/BV1TM4y1T7sw"].
Updated 2024/8/07: the new-theme card parsing is broken; below is the effect preview
card effect
To achieve the gradient background of the card, we usually add a background gradient with the linear-gradient style inside the background property. At first I planned to fetch the video cover from the Bilibili API and apply it directly to background, but during testing I found that Bilibili's image host has anti-hotlink enabled, so the image couldn't be used directly. After some trial and error I found two work-arounds.
A roundabout way
Anti-hotlink usually relies on the resource server checking the request's Referer header, allowing only requests from specified referrers. If the Referer points to a non-whitelisted page, the resource is denied and the image fails to load.
HTML has a referrerpolicy attribute that controls whether the browser sends a Referer header when a user clicks a link or initiates a request. When referrerpolicy is set to no-referrer, the browser will not send the Referer header, so the resource server gets no referrer information. If the resource server does not block empty Referer, you can bypass anti-hotlink by adding referrerpolicy="no-referrer" to the <img> tag.
Note
The <div> tag does not support the referrerpolicy="no-referrer" attribute.
Because <img> can't apply a background gradient directly in the style attribute, we need an extra gradient overlay:
After the browser finishes loading the image in the <img> tag, the <div>'s background will load from cache, indirectly solving the issue that <div> doesn't support referrerpolicy="no-referrer".
Third-party image cache
Another approach is to use a proxy to bypass anti-hotlink, which can be done with this PHP snippet:
CodeBlock Loading...
Or use a third-party image caching service, here https://images.weserv.nl is used. Just append the target image URL after https://images.weserv.nl/?url= and anti-hotlink is bypassed.
Warning
Finally, a reminder: don't upload images containing sensitive data to third-party sites, and don't abuse their services—no one wants the service to disappear one day.