【问题标题】:how to pass a parameter to a server-side bookmarklet?如何将参数传递给服务器端书签?
【发布时间】:2011-10-26 13:30:47
【问题描述】:

我有这个书签,它遵循this topic 中的建议:

javascript: (function () {  
    var jsCode = document.createElement('script');  
    jsCode.setAttribute('src', 'http://path/to/external/file.js');  
  document.body.appendChild(jsCode);  
 }());

我的问题是,我怎样才能给服务器脚本一些参数(例如页面标题)? 服务器脚本如下(目前只是一些 PoC):

(function(message){
    alert(message + " " + Math.random()*100);
})();

【问题讨论】:

  • 服务器脚本是什么意思?
  • 服务器脚本我的意思是小书签在执行时运行的脚本。这样主要逻辑是服务器端的,可以很容易地更新。

标签: javascript bookmarklet


【解决方案1】:

要将参数传递给服务器端脚本,请扩展查询字符串:

    jsCode.setAttribute('src', 'http://path/to/external/file.js?parameter=' + document.title);

如果您打算将参数传递给返回的脚本,请将onload 处理程序添加到脚本元素:

javascript:(function() {
    var jsCode = document.createElement('script');  
    var parameter = document.title; //Define parameter
    jsCode.onload = function() {
        // If the function exists, use:
        if(typeof special_func == "function") special_func(parameter);
    };
    jsCode.setAttribute('src', 'http://path/to/external/file.js');
    document.body.appendChild(jsCode);
})();

响应脚本(file.js):

function special_func(param){
    alert(param);
}

更新/示例

如果您想将(多个)变量传递给响应脚本,请使用以下代码:

javascript:(function() {
    var jsCode = document.createElement('script');  
    var params = ["test", document.title]; //Define parameter(s)
    var thisObject = {}; // `this` inside the callback function will point to
                         // the object as defined here.
    jsCode.onload = function() {
        // If the function exists, call it:
        if (typeof special_func == "function") {
            special_func.apply(thisObject, params);
        }
    };
    jsCode.setAttribute('src', 'http://path/to/external/file.js');
    document.body.appendChild(jsCode);
})();

http://path/to/external/file.js:

// Declare / Define special_func
var special_func = (function(){
    var local_variable = "password";
    var another_local_title = "Expected title";

    //Return a function, which will be stored in the `special_func` variable
    return function(string, title){ //Public function
        if (title == another_local_title) return local_variable;
    }
})();

【讨论】:

  • 是的,我试过了,但弹出窗口总是返回“未定义”。即使 URL 中的参数名称与匿名函数中的参数名称匹配。
  • 函数应该是匿名的。你应该在你的 JavaScript 中至少包含一个公共方法。我会用一个例子来更新我的答案。
  • 谢谢,这行得通!虽然我花了一些时间才发现丢失的“;”在你的第二个样本中。应该在 jsCode.onload 指令之后添加。
  • @Antoine public_function should have been function`。我已经改进了答案。
  • @lukiahas 感谢suggested edit。可惜被审稿人拒绝了,所以我自己加了。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-02-22
  • 1970-01-01
  • 2023-03-14
  • 2022-08-19
相关资源
最近更新 更多