-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathmain.js
416 lines (370 loc) · 12.7 KB
/
main.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
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
window.onload = function () {
changeURL();
};
const dateHeader = `### ${new Date().toLocaleDateString("en-GB", {
day: "numeric",
month: "short",
year: "numeric",
})}`;
/**
* Changes the URL of certain links on the page based on the chart redirect state and kite enabled state.
* Adds a copy button next to the modified links.
*/
function changeURL() {
// Get the chart redirect state from the background script
browser.runtime.sendMessage(
{ message: "getChartRedirectState" },
function (response) {
if (!response.chartRedirectState) {
return;
}
// Find all links with href starting with "/stocks"
var links = document.querySelectorAll('a[href^="/stocks"]');
for (var i = 0; i < links.length; i++) {
// Modify the href to redirect to TradingView with the appropriate symbol
links[
i
].href = `https://in.tradingview.com/chart/?symbol=NSE:${compatabilitySymbolFunc(
links[i].href
)}`;
}
}
);
// Get the kite enabled state from the background script
browser.runtime.sendMessage(
{ message: "getKiteEnabled" },
function (response) {
if (!response.kiteEnabled) {
return;
}
// Get the chart redirect state again
browser.runtime.sendMessage(
{ message: "getChartRedirectState" },
function (response) {
var links = [];
if (response.chartRedirectState) {
// Find all links with href starting with "https://in.tradingview.com/chart/?symbol=NSE:"
links = document.querySelectorAll(
'a[href^="https://in.tradingview.com/chart/?symbol=NSE:"]'
);
} else {
// Find all links with href starting with "/stocks"
links = document.querySelectorAll('a[href^="/stocks"]');
}
for (var i = 0; i < links.length; i++) {
// Skip every other link if not on the dashboard page
if (i % 2 !== 0 && !window.location.href.includes("/dashboard/")) {
continue;
}
// Skip if a copy button already exists
if (links[i].parentNode.querySelector(".copy-to-kite")) {
continue;
}
// Create a copy button
const copyButton = document.createElement("button");
copyButton.innerHTML = `<img src="https://kite.zerodha.com/static/images/browser-icons/apple-touch-icon-57x57.png" alt="copy" style="width: 20px; height: 20px; margin-bottom:-3px;">`;
copyButton.style.backgroundColor = "transparent";
copyButton.style.border = "none";
copyButton.style.cursor = "pointer";
copyButton.style.marginLeft = "5px";
copyButton.className = "copy-to-kite";
// Add an onclick event to the copy button
copyButton.onclick = function () {
const parentNode = copyButton.parentNode;
const aTagInParentNode = parentNode.querySelector("a");
const href = aTagInParentNode.href;
// Send a message to the background script to redirect to Kite with the copied link
browser.runtime.sendMessage({
message: "redirectToKite",
href: href,
});
};
// Append the copy button to the parent node of the link
links[i].parentNode.appendChild(copyButton);
}
}
);
}
);
}
/**
* Extracts the symbol from the URL based on the URL format.
* @param {string} url - The URL of the link.
* @returns {string|null} - The extracted symbol or null if not found.
*/
function compatabilitySymbolFunc(url) {
if (url.includes("stocks-new")) {
return new URL(url).searchParams.get("symbol");
}
return url.substring(url.lastIndexOf("/") + 1, url.lastIndexOf(".html"));
}
// Create a mutation observer to detect changes in the DOM
var observer = new MutationObserver(function (mutations) {
mutations.forEach(function (mutation) {
setTimeout(function () {
changeURL();
}, 100);
});
});
var config = {
childList: true,
subtree: true,
};
// Observe the document body for changes
observer.observe(document.body, config);
const screenerButtonsClass = "btn btn-default btn-primary";
/**
* Adds a copy button to the TradingView screener buttons.
* @param {string} buttonText - The text to display on the button.
* @param {string} buttonClass - The CSS class of the button.
* @param {string} buttonId - The ID of the button.
* @param {function} buttonFunction - The function to execute when the button is clicked.
*/
const addCopyToTradingViewButton = (
buttonText,
buttonClass,
buttonId,
buttonFunction
) => {
const screenerButtons = document.getElementsByClassName(screenerButtonsClass);
if (screenerButtons.length === 0) return;
const screenerButtonsParent = screenerButtons[0].parentNode;
const screenerButton = document.createElement("button");
screenerButton.innerHTML = buttonText;
screenerButton.className = buttonClass;
screenerButton.id = buttonId;
screenerButton.onclick = buttonFunction;
screenerButtonsParent.appendChild(screenerButton);
};
// Add a copy button to the TradingView screener buttons
addCopyToTradingViewButton(
"Copy to TradingView",
"btn btn-default btn-primary",
"add-to-watchlist",
copyAllTickersOnScreen
);
/**
* Gets the length of the pagination.
* @returns {number} - The length of the pagination.
*/
function getPaginationLength() {
const paginationList = document
.getElementsByClassName("pagination")[0]
.getElementsByTagName("li");
return paginationList[paginationList.length - 2].innerText;
}
// Clicks the next page button
function nextPage() {
document
.evaluate(
"//a[text()='Next']",
document,
null,
XPathResult.FIRST_ORDERED_NODE_TYPE,
null
)
.singleNodeValue.click();
}
/**
* Gets the number of stocks displayed on the screen.
* @returns {number} - The number of stocks.
*/
function getNumberOfStocks() {
const el = document.getElementsByClassName("dataTables_info")[0];
const innerText = el.innerText;
const numberOfStocks = innerText.match(/\d+/)[0];
return numberOfStocks;
}
/**
* Delays the execution of the code.
* @param {number} t - The delay time in milliseconds.
* @returns {Promise} - A promise that resolves after the delay.
*/
const delay = (t) => {
return new Promise((res) => setTimeout(res, t));
};
/**
* Copies all the tickers on the screen to the clipboard.
*/
async function copyAllTickersOnScreen() {
// Get the chart redirect state from the background script
browser.runtime.sendMessage(
{ message: "getChartRedirectState" },
async function (response) {
if (response.chartRedirectState) {
let allTickersArray = [];
let allTags = [];
const numberOfPages = getPaginationLength();
// Iterate through each page
for (let i = 0; i < numberOfPages; i++) {
if (i > 0) {
await delay(200);
}
// Find all tags with href starting with "https://in.tradingview.com/chart/?symbol=NSE:"
allTags.push(
document.querySelectorAll(
'a[href^="https://in.tradingview.com/chart/?symbol=NSE:"]'
)
);
nextPage();
}
// Flatten the array of tags
const allTickers = allTags.map((tag) => Array.from(tag)).flat();
// Extract the symbols from the URLs and add them to the tickers array
allTickers.forEach((ticker) => {
allTickersArray.push(
replaceSpecialCharsWithUnderscore(
extracrtSymbolFromURL(ticker.href)
)
);
});
// Add "NSE:" prefix to the tickers
allTickersArray = addColonNSEtoTickers(allTickersArray);
// Create a fake textarea to copy the tickers to the clipboard
createFakeTextAreaToCopyText(
[...removeDuplicateTickers(allTickersArray)].join(", ")
);
replaceButtonText("add-to-watchlist");
return;
}
let allTickersArray = [];
let allTags = [];
const numberOfPages = getPaginationLength();
console.log(numberOfPages);
// Iterate through each page
for (let i = 0; i < numberOfPages; i++) {
if (i > 0) {
await delay(200);
}
allTags.push(document.querySelectorAll('a[href^="/stocks-new"]'));
nextPage();
}
console.log(allTags);
// Flatten the array of tags
const allTickers = allTags.map((tag) => Array.from(tag)).flat();
// Extract the symbols from the URLs and add them to the tickers array
allTickers.forEach((ticker) => {
allTickersArray.push(
replaceSpecialCharsWithUnderscore(
extractSymbolFromTradingViewURL(ticker.href)
)
);
});
// Add "NSE:" prefix to the tickers
allTickersArray = addColonNSEtoTickers(allTickersArray);
// Create a fake textarea to copy the tickers to the clipboard
createFakeTextAreaToCopyText(
[...removeDuplicateTickers(allTickersArray)].join(", ")
);
replaceButtonText("add-to-watchlist");
}
);
}
/**
* Replaces the text of a button with a success message and then restores it after a delay.
* @param {string} buttonId - The ID of the button.
*/
function replaceButtonText(buttonId) {
const button = document.getElementById(buttonId);
if (!button) return;
button.innerHTML = "Copied to clipboard 📋";
setTimeout(() => {
button.innerHTML = "Copy to TradingView";
}, 2000);
}
/**
* Creates a fake textarea, copies the text to it, and then copies the text from the textarea to the clipboard.
* @param {string} text - The text to copy to the clipboard.
*/
function createFakeTextAreaToCopyText(text) {
const fakeTextArea = document.createElement("textarea");
fakeTextArea.value = `${dateHeader},${text}`;
document.body.appendChild(fakeTextArea);
fakeTextArea.select();
document.execCommand("copy");
document.body.removeChild(fakeTextArea);
}
/**
* Removes duplicate tickers from an array.
* @param {string[]} tickers - The array of tickers.
* @returns {string[]} - The array of tickers with duplicates removed.
*/
function removeDuplicateTickers(tickers) {
return [...new Set(tickers)];
}
/**
* Adds "NSE:" prefix to each ticker in an array.
* @param {string[]} tickers - The array of tickers.
* @returns {string[]} - The array of tickers with "NSE:" prefix added.
*/
function addColonNSEtoTickers(tickers) {
return tickers.map((ticker) => `NSE:${ticker}`);
}
/**
* Replaces special characters in a ticker with underscores.
* @param {string} ticker - The ticker.
* @returns {string} - The ticker with special characters replaced.
*/
function replaceSpecialCharsWithUnderscore(ticker) {
return ticker.replace(/[^a-zA-Z0-9]/g, "_");
}
/**
* Adds copy buttons to the TradingView charts.
*/
const addCopyBtOnTradingView = () => {
const copyBts = document.querySelectorAll('i[class="far fa-copy mr-1"]');
copyBts.forEach((copyBt) => {
copyBt.style.fontSize = "20px";
copyBt.onclick = (e) => {
e.stopPropagation();
const tables =
copyBt.parentNode.parentNode.parentNode.parentNode.parentNode.querySelector(
"table"
);
const allTickers = tables.querySelectorAll(
'a[href^="https://in.tradingview.com/chart/?symbol=NSE:"]'
);
let allTickersArray = [];
allTickers.forEach((ticker) => {
allTickersArray.push(
replaceSpecialCharsWithUnderscore(ticker.href.substring(45))
);
});
allTickersArray = addColonNSEtoTickers(allTickersArray);
createFakeTextAreaToCopyText(
removeDuplicateTickers(allTickersArray).join(",")
);
alert("Copied to clipboard 📋");
};
});
};
// Add copy buttons to the TradingView charts
addCopyBtOnTradingView();
/**
* Removes the ".html" extension from a ticker.
* @param {string} ticker - The ticker.
* @returns {string} - The ticker without the ".html" extension.
*/
function removeDotHTML(ticker) {
return ticker.replace(".html", "");
}
/**
* Extracts the symbol from the URL.
* @param {string} url - The URL of the link.
* @returns {string|null} - The extracted symbol or null if not found.
*/
function extracrtSymbolFromURL(url) {
const urlParams = new URLSearchParams(new URL(url).search);
const symbol = urlParams.get("symbol");
return symbol ? symbol.split(":")[1] : null;
}
function extractSymbolFromTradingViewURL(url) {
if (url.includes("NSE:")) {
return url.split("/")[4].split(":")[1];
} else if (url.includes("/stocks-new")) {
const urlParams = new URLSearchParams(url);
return urlParams.get("symbol");
} else if (url.includes("/stocks/")) {
return url.split("/").pop().replace(".html", "");
}
}