-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnewtab.js
187 lines (156 loc) · 5.86 KB
/
newtab.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
// Unsplash API credentials
const UNSPLASH_ACCESS_KEY = 'hHHVDs662n4UiT2Qlz5SZa3x1CCEvn8i8JG7SgJ9z1I';
const CARS_QUERY = 'mountains,forests,lakes,rivers,oceans,waterfalls,sunsets,sunrises,beaches,deserts,fields,meadows,parks,wildlife,animals,birds,trees,flora,fauna,landscapes,natural_world,wildlife_photography,eco_tourism,greenery,earth,planet_earth,nature_lovers,natural_beauty';
// Variables to hold image data
let currentImage = null;
let nextImage = null;
let isSponsored = false;
let usingFallback = false;
// Simple fallback image system
const fallbackImages = [
'../images/img1.jpg',
'../images/img2.jpg',
'../images/img3.jpg',
'../images/img4.jpg',
'../images/img5.jpg'
];
// Get a random fallback image
function getRandomFallbackImage() {
const randomIndex = Math.floor(Math.random() * fallbackImages.length);
return fallbackImages[randomIndex];
}
// Initialize the new tab page
document.addEventListener('DOMContentLoaded', () => {
updateDateTime();
setInterval(updateDateTime, 1000);
loadAndSetBackgroundImage();
// Listen for online event to switch back to Unsplash
window.addEventListener('online', () => {
if (usingFallback) {
console.log('Internet connection restored. Switching back to Unsplash.');
usingFallback = false;
loadAndSetBackgroundImage();
}
});
});
// Update time and date
function updateDateTime() {
const now = new Date();
// Update time
const hours = now.getHours().toString().padStart(2, '0');
const minutes = now.getMinutes().toString().padStart(2, '0');
const seconds = now.getSeconds().toString().padStart(2, '0');
document.getElementById('time').textContent = `${hours}:${minutes}:${seconds}`;
// Update date
const options = { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' };
document.getElementById('date').textContent = now.toLocaleDateString(undefined, options);
}
// Load and set background image
async function loadAndSetBackgroundImage() {
try {
// If we're not in fallback mode, try to load from Unsplash/sponsored
if (!usingFallback) {
// Check if next image is already loaded
if (nextImage) {
setBackgroundImage(nextImage);
currentImage = nextImage;
nextImage = null;
} else {
// If no next image, load a new one
const imageData = await getImageToDisplay();
setBackgroundImage(imageData);
currentImage = imageData;
}
// Prefetch next image for future use
prefetchNextImage();
}
} catch (error) {
console.error('Error loading background image:', error);
// Switch to fallback mode
usingFallback = true;
// Get a random fallback image
const fallbackImage = getRandomFallbackImage();
document.body.style.backgroundImage = `url('${fallbackImage}')`;
// Update attribution for fallback
const photographerLink = document.getElementById('photographer-link');
photographerLink.textContent = 'Local Fallback Image';
photographerLink.href = '#';
// Hide sponsored tag for fallback
document.getElementById('sponsored-tag').style.display = 'none';
}
}
// Get image to display (either from Unsplash or sponsored)
async function getImageToDisplay() {
const settings = await chrome.storage.sync.get({
showSponsored: true,
sponsoredFrequency: 5,
imageCount: 0
});
// Increment image count
const imageCount = settings.imageCount + 1;
await chrome.storage.sync.set({ imageCount });
// Check if we should show a sponsored image
if (settings.showSponsored && imageCount % settings.sponsoredFrequency === 0) {
const sponsoredImage = await getSponsoredImage();
if (sponsoredImage) {
isSponsored = true;
document.getElementById('sponsored-tag').style.display = 'block';
return sponsoredImage;
}
}
// Otherwise get image from Unsplash
isSponsored = false;
document.getElementById('sponsored-tag').style.display = 'none';
return getUnsplashImage();
}
// Get a random car image from Unsplash
async function getUnsplashImage() {
const response = await fetch(`https://api.unsplash.com/photos/random?query=${CARS_QUERY}&orientation=landscape&count=1`, {
headers: {
'Authorization': `Client-ID ${UNSPLASH_ACCESS_KEY}`
}
});
if (!response.ok) {
throw new Error('Failed to fetch image from Unsplash');
}
const data = await response.json();
const image = data[0];
return {
url: image.urls.full,
photographer: image.user.name,
photographerUrl: image.user.links.html,
isSponsored: false
};
}
// Get a sponsored image from storage
async function getSponsoredImage() {
const { sponsoredImages } = await chrome.storage.sync.get({ sponsoredImages: [] });
if (sponsoredImages.length === 0) {
return null;
}
// Get a random sponsored image
const randomIndex = Math.floor(Math.random() * sponsoredImages.length);
return sponsoredImages[randomIndex];
}
// Set the background image and attribution
function setBackgroundImage(imageData) {
document.body.style.backgroundImage = `url('${imageData.url}')`;
// Update attribution
const photographerLink = document.getElementById('photographer-link');
photographerLink.textContent = imageData.photographer;
photographerLink.href = imageData.photographerUrl;
// Show/hide sponsored tag
document.getElementById('sponsored-tag').style.display = imageData.isSponsored ? 'block' : 'none';
}
// Prefetch the next image
async function prefetchNextImage() {
try {
nextImage = await getImageToDisplay();
// Preload the image
const img = new Image();
img.src = nextImage.url;
} catch (error) {
console.error('Error prefetching next image:', error);
nextImage = null;
}
}