1
- import ogs from "https://esm.sh/[email protected] /" ;
1
+ // Simple Open Graph scraper implementation for Deno/Edge Functions
2
+ async function extractOgImage ( url ) {
3
+ try {
4
+ const response = await fetch ( url , {
5
+ redirect : 'follow' ,
6
+ headers : {
7
+ 'Accept' : 'text/html' ,
8
+ 'user-agent' : 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/112.0.0.0 Safari/537.36'
9
+ }
10
+ } ) ;
11
+
12
+ if ( ! response . ok ) {
13
+ return false ;
14
+ }
15
+
16
+ const html = await response . text ( ) ;
17
+
18
+ // Extract og:image using regex (simple approach for edge functions)
19
+ const ogImageMatch = html . match ( / < m e t a \s + p r o p e r t y = [ " \' ] o g : i m a g e [ " \' ] \s + c o n t e n t = [ " \' ] ( [ ^ " \' ] + ) [ " \' ] [ ^ > ] * > / i) ;
20
+ if ( ogImageMatch && ogImageMatch [ 1 ] ) {
21
+ return ogImageMatch [ 1 ] ;
22
+ }
23
+
24
+ // Fallback to other image meta tags
25
+ const twitterImageMatch = html . match ( / < m e t a \s + n a m e = [ " \' ] t w i t t e r : i m a g e [ " \' ] \s + c o n t e n t = [ " \' ] ( [ ^ " \' ] + ) [ " \' ] [ ^ > ] * > / i) ;
26
+ if ( twitterImageMatch && twitterImageMatch [ 1 ] ) {
27
+ return twitterImageMatch [ 1 ] ;
28
+ }
29
+
30
+ return false ;
31
+ } catch ( error ) {
32
+ console . error ( 'Error extracting OG image:' , error ) ;
33
+ return false ;
34
+ }
35
+ }
2
36
3
37
export default async function ogImage ( req ) {
4
38
@@ -10,28 +44,10 @@ export default async function ogImage( req ) {
10
44
return new Response ( '' , { status : '511' } ) ;
11
45
}
12
46
13
- url = url . searchParams . get ( 'url' ) ;
14
- const fetchOptions = {
15
- redirect : 'follow' ,
16
- headers : {
17
- 'Accept' : 'text/html' ,
18
- 'user-agent' : 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/112.0.0.0 Safari/537.36'
19
- }
20
- } ;
47
+ const targetUrl = url . searchParams . get ( 'url' ) ;
21
48
22
- let image = false ;
23
- ogs ( { url, fetchOptions } )
24
- . then ( data => {
25
- const { error, result, response } = data ;
26
- if ( ! error && result . success ) {
27
- image = result . ogImage [ 0 ] . url ;
28
- }
29
- else
30
- {
31
- console . log ( 'Failed Response:' , response ) ;
32
- }
33
- } ) ;
34
- console . log ( image ) ;
49
+ const image = await extractOgImage ( targetUrl ) ;
50
+ console . log ( 'Extracted image:' , image ) ;
35
51
36
52
return new Response ( JSON . stringify ( { image } ) ) ;
37
53
}
0 commit comments