【问题标题】:Javascript bookmarklet: how to replace URL parts?Javascript 小书签:如何替换 URL 部分?
【发布时间】:2011-11-07 10:23:14
【问题描述】:

我正在尝试创建一个 Javascript 小书签,它将从 URL 中提取数字 ID:

   http://site-1/script-1.php?ID=12345678&other-params

然后将浏览器重定向到一个新的 URL:

   http://site-2/script-2.php?id=12345678

我已经在网上搜索了书签示例,我有 2 个问题:

1) 我需要将我的 JS 代码放在 void 中吗?

javascript:void(XXX);

void 在这种情况下是什么意思?

2) 我应该使用 location.href 来读取旧 URL 并分配一个新构建的 URL 吗?我之所以问,是因为我见过许多奇怪的代码,例如 String(location.href) 等 - 就像它需要对 String 进行一些 casting (是吗? )

更新:我尝试了以下代码,但不幸的是,当我在旧页面上并单击我的书签(希望导航到新页面)时,Chrome 中没有任何反应:

javascript:void (
    if ( var match = location.search.match(/id=(\d+)/i) ) 
        location = 'http://site-2/script-2.php?id=' + match[1];
)

(我在上面添加了换行符,是的,我正在尝试使用单个“=”)

更新 2:我的第二次尝试 - 只是尝试显示一个新 URL:

javascript:void (
    var match = location.search.match(/ID=(\d+)/);
    alert('http://site-2/script-2.php?id=' + match[1]);
)

但当我单击书签栏上的书签时,仍然没有任何反应。我在 Google Chrome 控制台中看到:

Uncaught SyntaxError: Unexpected token var

【问题讨论】:

    标签: javascript bookmarklet


    【解决方案1】:

    1) 如果您的小书签返回一个值,以便在所有代码运行后,该 url 可以读取为:javascript:%somestring%,浏览器将在浏览器窗口中显示该字符串。所以void() 只是防止意外覆盖文档的保护措施(ref...The void operator evaluates the given expression and then returns undefined...)。这意味着,如果你小心,你就不需要 void。

    2) 不需要强制转换,如果你不提供字符串值,它会自动发生。


    我的书签模板:

    <a href="javascript:(function(){
      // do stuff but do not return anything
    }());">something</a>
    

    更新:

    javascript:(function () {
      var match = window.location.href.match(/ID=(\d+)/);
      if (match.length > 0) {
        alert('http://site-2/script-2.php?id=' + match[1]);
        // or after debugging: window.location = 'http://site-2/script-2.php?id=' + match[1];
      }
    }());
    

    【讨论】:

    • var in an if condition is invalid syntax ;) (在 if 之前声明匹配,然后使用它)
    • 使用match 而不是search。 (location.match)
    • 谢谢,我确实想要 location.search.match()。我已经更新了我的代码 - 仍然没有显示警报弹出窗口。
    • 谢谢,但同样的问题:Uncaught SyntaxError: Unexpected token var
    猜你喜欢
    • 1970-01-01
    • 2011-08-23
    • 2018-12-21
    • 1970-01-01
    • 1970-01-01
    • 2017-01-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多