【问题标题】:How can I add a parameter to a URL and then reload the page using Greasemonkey?如何向 URL 添加参数,然后使用 Greasemonkey 重新加载页面?
【发布时间】:2013-03-06 20:08:19
【问题描述】:

如果您未登录,Quora 网站的大部分内容都会模糊掉。解决此问题的一种方法是在其 URL 中添加参数“?share=1”。我认为通过 Greasemonkey 执行此操作的步骤是:

0/ 存储当前 URL

1/ 检查参数是否已经存在。如果是,请打破。

2/如果没有,添加参数。

3/ 使用更新后的 URL 重新加载。

它类似于this question,但在我看来,这可以在没有正则表达式的情况下完成?我可能是错的。

这是我正在尝试使用的代码:

// ==UserScript==
// @name       Quora Share
// @namespace  kevmo.info
// @version    0.1
// @description  adds "?share=1" to URLS, i.e. let's you view full Quora content w/o being logged in.
// @include      https://*.quora.com/*
// @include      http://*quora.com/*
// @copyright  Creative Commons
// ==/UserScript==

var url = window.location.href;

if (url.indexOf("?share=1") !== -1){
    break;
}
else{
    url +="?share=1";
    window.location.replace(url)
}

注意:在“设置”中,我将脚本设置为在文档开始时运行。

我知道这种基本方法不适用于其他网站,但仅附加“?share=1”应该在 Quora 上工作(请参阅:http://blog.quora.com/Making-Sharing-Better

当我访问 http://www.quora.com/Animals/What-are-some-mind-blowing-facts-from-the-animal-kingdom 时,页面没有重新加载所需的新 URL 并添加了参数。

【问题讨论】:

  • 您不想在 URL 的末尾添加 ?share=1,因为 URL 可能已经有 URL 参数和/或哈希 (#)。这样做会破坏 URL。 (如果没有任何其他 URL 参数或哈希值,您当前的代码将起作用。)使用与您链接的问题相同的方法。
  • 我相信这对 Quora 有用:blog.quora.com/Making-Sharing-Better
  • 你有问题中的脚本。它有效吗?如果没有,它是如何失败的?如果是,或者您还没有尝试过,为什么要问这个问题? ... 最后,即使它看起来现在可以工作,它在某些情况下或当站点发生变化时会失败——原因我在上面给出。 ..不要在没有该死的充分理由的情况下重新发明轮子。链接方法已被反复验证,并且在设计时考虑了 URL 的结构。
  • 感谢您提出的富有洞察力的问题,Brock。我编辑了问题详细信息以解决它们。

标签: javascript dom greasemonkey


【解决方案1】:

元编辑:您使用的是“break;”而不是循环结构。

    function share_redirect() {
    var new_url = false;

    if (window.location.hash.length === 0  && window.location.search.lenth === 0) {
         new_url = window.location.href+"?share=1"
    } else {

         if (window.location.search.indexOf('share=1') != -1) {
             return false; // already sharing
         }

         if (window.location.search.length && window.location.hash.length) {

             new_url = window.location.href.split('#')[0]+"&share=1"+window.location.hash;
         } else if (window.location.search.length === 0 && window.location.hash.length) {
             new_url = window.location.href.split('#')[0]+"?share=1"+window.location.hash;
         } else {
             new_url = window.location.href+"&share=1";
         }
    }
    if (new_url) {
        window.location = new_url;
    }
}

【讨论】:

  • 条件的第一行有拼写错误 - 长度为 lenth。无法更正,因为至少需要 6 个字符。投票赞成。
猜你喜欢
  • 2014-04-14
  • 2019-03-08
  • 1970-01-01
  • 1970-01-01
  • 2016-04-10
  • 2011-09-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多