油猴脚本修改sciencedirect论文下载名

一、说明:

最近下载论文时 发现无法下载pdf,刚好在学JS,就一边学习一边编了一个脚本。代码很烂,功能基本符合预期。

二、v1.0功能:

当用户拥有Access权限时,生成dowload按钮,调用sciencedirect官方下载,下载文件名默认为文章名。
在这里插入图片描述

当用户没有Access权限时,调用scihub下载。
在这里插入图片描述

三、脚本地址:

https://greasyfork.org/zh-CN/scripts/451690-sciencedirect-download

四、脚本代码:

// ==UserScript==
// @name                ScienceDirect Download
// @name:zh-CN          ScienceDirect下载
// @namespace      tampermonkey.com
// @version        1.0
// @license MIT
// @description         Avoid jumping to online pdf, and directly download ScienceDirect literature to local
// @description:zh-CN   避免跳转在线pdf,可直接下载ScienceDirect文献到本地
// @match        *://www.sciencedirect.com/*
// @match        *://pdf.sciencedirectassets.com/*
// @grant        GM_setValue
// @grant        GM_getValue
// @run-at document-start
// ==/UserScript==
function getBlob(url, cb) {
    var xhr = new XMLHttpRequest();
    xhr.open('GET', url, true);
    xhr.responseType = 'blob';
    xhr.onload = function () {
        if (xhr.status === 200) {
            cb(xhr.response);
        }
    };
    xhr.send();
};
function saveAs(blob, filename) {
    if (window.navigator.msSaveOrOpenBlob) {
        navigator.msSaveBlob(blob, filename);
    } else {
        var link = document.createElement('a');
        var body = document.querySelector('body');
        link.href = window.URL.createObjectURL(blob);
        link.download = filename;
        // fix Firefox
        link.style.display = 'none';
        body.appendChild(link);
        link.click();
        body.removeChild(link);
        window.URL.revokeObjectURL(link.href);
    }
}

function download(url, filename) {
    getBlob(url, function (blob) {
        saveAs(blob, filename);
    });
}
(function () {
    'use strict';
    var domain = document.domain;
    if (domain == 'pdf.sciencedirectassets.com') {
        var url = document.URL + '&download=true';
        console.log(url);
        var title = document.URL.split("/")[5].split("-")[2];
        try {
            var id = document.URL.split("/")[5].split("-")[2]
            title = GM_getValue(id)
        } catch (err) {
            console.log("err_message" + err.message);
        }
        // var html_url = "https://www.sciencedirect.com/science/article/pii/" + document.URL.split("/")[5].split("-")[2]
        var ret = prompt('Type your filename and click confirm to download!', title);
        if (ret !== null && ret != '') {
            var filename = ret + '.pdf';
            download(url, filename);
        }
    }
    if (domain == 'www.sciencedirect.com') {
        document.addEventListener('DOMContentLoaded', (event) => {
            console.log('DOM加载完成.');
            var linkid = document.head.getElementsByTagName('meta')[0].content;
            var titile = document.title.replace(' - ScienceDirect', '');
            GM_setValue(linkid, titile);
            var access = document.querySelector("#mathjax-container > div.sticky-outer-wrapper > div > div.accessbar > ul > li:nth-child(1) > a").href.split('login')[1];
            var doi = document.getElementsByClassName('doi')[0].href.split('org')[1];
            GM_setValue('access', access);
            if (GM_getValue('access')) {
                var scihubs = ['http://sci-hub.ren', 'https://sci-hub.ru/', 'https://sci-hub.se/', 'https://sci-hub.ee/', 'https://sci-hub.shop/', 'https://sci-hub.ren/', 'https://sci-hub.st/'];
                var scihub = scihubs[Math.floor(Math.random() * scihubs.length)];
                new_url = scihub + doi;
                var ret = prompt('Type scihub address!', scihub);
                if (ret !== null && ret != '') {
                    new_url = ret + doi;
                    window.location.href = new_url
                } else { }
            } else {
                var new_url = "https://www.sciencedirect.com/science/article/pii/" + linkid + "/pdfft?isDTMRedir=true";
                console.log(new_url);
                let Container = document.createElement('div')
                Container.id = "sp-ac-container";
                Container.style.position = "fixed";
                Container.style.left = "250px";
                Container.style.top = "28px";
                Container.style['z-index'] = "2";
                Container.innerHTML = `<button title="Click to download" class="button1" id="download" οnclick="window.location.href='${new_url}'")>download</button>
                                        <style>
                                        .button1 {
                                        -webkit-transition-duration: 0.4s;
                                        transition-duration: 0.4s;
                                        padding: 1.5px 6px;
                                        text-align: center;
                                        background-color: #f5f5f5;
                                        color: rgb(243, 109, 33);
                                        border: 0.5px rgb(134, 218, 209);
                                        border-radius: 9px;
                                        font-family: NexusSans,Arial,Helvetica,Lucida Sans Unicode,Microsoft Sans Serif,Segoe UI Symbol,STIXGeneral,Cambria Math,Arial Unicode MS,sans-serif!important;
                                        }
                                        .button1:hover {
                                        background-color: rgb(134, 218, 209);;;
                                        color: red;
                                        }
                                        </style>`;
                document.body.appendChild(Container);
            }
        });
    }
})()

五、v1.0脚本说明:

GM_setValue, GM_getValue使用油猴插件存储变量
@run-at document-start在页面加载前运行脚本
prompt() 函数用于弹出提示用户进行输入信息的文本框,其返回用户输入的字符串。

六、油猴基本权限

油猴的脚本需要包含很多属性,以便油猴识别你想在什么页面执行,需要什么api和权限,你脚本的一些作者信息支持网站是什么,等等.

@name
@namespace
@copyright
@version
@description
@icon, @iconURL, @defaulticon
@icon64, @icon64URL
@grant
@author
@homepage, @homepageURL, @website, @source
@antifeature
@require
@resource
@include
@match
@exclude
@run-at
@sandbox
@connect
@noframes
@updateURL
@downloadURL
@supportURL
@webRequest
@unwrap

内置程序接口:

unsafeWindow
Subresource Integrity
GM_addElement(tag_name, attributes), GM_addElement(parent_node, tag_name, attributes)
GM_addStyle(css)
GM_download(details), GM_download(url, name)
GM_getResourceText(name)
GM_getResourceURL(name)
GM_info
GM_log(message)
GM_notification(details, ondone), GM_notification(text, title, image, onclick)
GM_openInTab(url, options), GM_openInTab(url, loadInBackground)
GM_registerMenuCommand(name, callback, options_or_accessKey)
GM_unregisterMenuCommand(menuCmdId)
GM_setClipboard(data, info)
GM_getTab(callback)
GM_saveTab(tab)
GM_getTabs(callback)
GM_setValue(key, value)
GM_getValue(key, defaultValue)
GM_deleteValue(key)
GM_listValues()
GM_addValueChangeListener(key, (key, old_value, new_value, remote) => void)
GM_removeValueChangeListener(listenerId)
GM_xmlhttpRequest(details)
GM_webRequest(rules, listener)
GM_cookie.list(details[, callback])
GM_cookie.set(details[, callback])
GM_cookie.delete(details, callback)
window.onurlchange
window.close
window.focus
<><![CDATA[...]]></>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

KmBase

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值