在Chrome的新标签中同时打开谷歌搜索结果
JavaScript,通常缩写为JS,是一种符合ECMAScript规范的高级、解释型编程语言。
jQuery是一个JavaScript库,旨在简化HTML DOM树的遍历和操作。
我们可以用它们来做各种各样的事情,而我们手动做这些事情是很累人的。
注意:在第一次运行脚本时,会有一个弹出窗口。我们必须允许弹出窗口,因为Chrome想知道我们是否要使用多个标签。然后重新运行该脚本。
如何运行:
在谷歌上搜索任何东西。在谷歌搜索结果页面上,将脚本粘贴到开发者工具控制台窗口,然后按回车键,就可以看到神奇的效果。
让我们看看这段代码。
// dynamically loading the jQuery library
javascript: var fileref = document.createElement('script');
fileref.setAttribute("type", "text/javascript");
fileref.setAttribute("src",
"https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js");
document.body.appendChild(fileref);
var arr = []; //this array will contain the links of google search results.
setTimeout(function() {
// We are using setTimeout function so that
// jQuery library is loaded fully before running
//rest part of the code
// Accessing the DOM and using it to extract
// links from the search results
var count1 = ("div.bkWMgd").length;
var j;
// There are many div's with this class "div.bkWMgd" but we
// will be using only the div's which will be
// containing the search results links,
// so we have to filter out the div's by performing if-else.
for (j = 0; j("div.bkWMgd")[j].firstChild == null) {
// not using this section because it does not contain the links
continue;
} else if
(("div.bkWMgd")[j].firstChild.className.toString().trim() === "srg") {
// This div contains the search result links
var count2 =("div.bkWMgd")[j].firstChild.children.length;
var i;
for (i = 0; i < count2; i++) {
arr.push(
("div.bkWMgd")[j].firstChild.children[i].children[0].
firstChild.firstChild.firstChild.href.toString().trim());
// inserting search results links into the array
}
count2 = 0;
continue;
} else if
(("div.bkWMgd")[j].firstChild.innerHTML.toString().trim()==="Web results") {
// This div also contains the search result links
("div.bkWMgd")[j].firstChild.remove();
var count2 =("div.bkWMgd")[j].firstChild.children.length;
try { // Handling error if encountered using try catch block
var i;
for (i = 0; i < count2; i++) {
arr.push(
$("div.bkWMgd")[j].firstChild.children[i].children[0].
firstChild.firstChild.firstChild.href.toString().trim());
} // inserting links into the array
count2 = 0;
} catch (err) {
console.log('Error handled in: ', j + 'loop');
}
}
}
}, 1000);
// opening multiple tabs with the links in the array
function open_win() {
for (var i = 0; i < arr.length; i++) {
console.log(arr[i]);
window.open(arr[i]);
}
}
// in 2.5 seconds multiple tabs will get
// open with the search results links
setTimeout(function() {
open_win();
}, 2500);
运行结果