Как передать параметр в серверный букмарклет? - PullRequest
0 голосов
/ 26 октября 2011

У меня есть этот букмарклет, который следует тому, что было предложено в этой теме :

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);
})();

1 Ответ

4 голосов
/ 26 октября 2011

Чтобы передать параметр в сценарий на стороне сервера, расширьте строку запроса:

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

Если вы собираетесь передать параметр в возвращаемый сценарий, добавьте обработчик onload вэлемент script:

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;
    }
})();
...