将 JavaScript 转换为用户脚本
Conversion of JavaScript to userscript
我有 JavaScript 运行 对服务器进行 ajax 调用。
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script type="text/javascript">
var div = '<div id="OverlayDialog">';
$.Coral = function (options) {
$.extend(options, {
data: JSON.stringify(options.data),
dataType: 'json',
type: 'POST',
async: false,
contentType: 'application/json',
processData: false,
headers: {
'Content-Encoding': 'abc',
'Target': options.operation
},
dataFilter: function(data, type) {
return data || "{}";
}
});
return $.ajax(options);
};
$.MyService = function (options) {
$.extend(options, {
url: "link to myservice",
operation: 'dummyOperation'
});
return $.Coral(options);
};
function test() {
try {
var myOptionsData = {
storeUrlList: [document.getElementById('normalizedStoreUrl1').value,document.getElementById('normalizedStoreUrl2').value]
};
var myOptions = {data: myOptionsData,crossDomain: true};
response = $.MyService(myOptions).responseText;
var subString = "";
var startIndex = response.indexOf('{',1);
var endIndex = response.lastIndexOf('}');
responseText = response.substring(startIndex,endIndex);
var subString = JSON.parse(responseText);
var map2 = new Map();
$.each( subString, function( key, value ) {
var map1 = new Map();
div+='<p>'+JSON.stringify(key)+'</p>';
$.each( value, function( ky, val ) {
console.log('ky => '+ky);
console.log('val => '+val);
map1.set(ky, val);
div += '<p>'+JSON.stringify(ky)+':'+JSON.stringify(val)+'</p>';
});
});
} catch(e) {
alert(e);
}
div += '</div>';
$('body').append(div);
return false;
}
</script>
脚本对我来说运行得很好。
我想将其转换为 greasemonkey 脚本,同时使用 jqueryUI 对话框在单独的对话框中显示结果。创建覆盖对话框并将数据写入其中的部分工作正常,但我无法在用户脚本中执行 .$MyOptions 和 .$Coral 函数。
下面是我使用的用户脚本:
// ==UserScript==
// @name Get Data for each unique URL
// @namespace SellerSupportScript
// @include *
// @require http://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js
// @require http://ajax.googleapis.com/ajax/libs/jquery/ui/1.11.0/jquery-ui.min.js
// @resource jqUI_CSS http://ajax.googleapis.com/ajax/libs/jqueryui/1.11.3/themes/redmond/jquery-ui.css
// @grant GM_addStyle
// @grant GM_getResourceText
// @grant GM_getResourceURL
// @run-at document-end
// allow pasting
// ==/UserScript==
var snapshotResults = document.evaluate('//a[contains(@href,"http")]/@href', document, null, XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE, null);
var windowWidth = $(window).width()-800;
var windowHeight = 'auto';
var div = '<div id="SSOverlayDialog">';
var zNode = document.createElement ('input');
zNode.setAttribute ('id', 'SSButton');
zNode.setAttribute( 'type', 'image' );
zNode.setAttribute( 'src', 'http://www.veryicon.com/icon/64/System/Longhorn%20R2/Back%20Button.png');
document.body.appendChild (zNode);
var uniqueHostnameSet = new Set();
var uniqueURLArray = [];
uniqueHostnameSet.add(window.location.hostname);
var finalUrl = window.location.protocol + '//' + window.location.hostname;
uniqueURLArray.push(finalUrl);
var linkToDisplay = '<a href="' + finalUrl + '">' + finalUrl + '</a>';
linkToDisplay += '<br/><br/>';
div += linkToDisplay;
for (var iterate = 0; iterate < snapshotResults.snapshotLength; iterate++)
{
var hrefContent = snapshotResults.snapshotItem(iterate).textContent;
var regex = /http.*/;
var href = regex.exec(hrefContent);
var a = document.createElement('a');
a.href = href;
if (!uniqueHostnameSet.has(a.hostname))
{
uniqueHostnameSet.add(a.hostname);
finalUrl = a.protocol + '//' + a.hostname;
uniqueURLArray.push(finalUrl);
linkToDisplay = '<a href="' + finalUrl + '">' + finalUrl + '</a>';
linkToDisplay += '<br/><br/>';
div += linkToDisplay;
}
}
var size = 10;
for (var i=0; i<uniqueURLArray.length; i+=size) {
var urlList = uniqueURLArray.slice(i,i+size);
try {
var myOptionsData = {
storeUrlList: urlList
};
var myOptions = {data: myOptionsData,crossDomain: true};
response = $.MyService(myOptions).responseText;
var subString = "";
var startIndex = response.indexOf('{',1);
var endIndex = response.lastIndexOf('}');
responseText = response.substring(startIndex,endIndex);
var subString = JSON.parse(responseText);
var AttributeMap = {};
var map2 = new Map();
$.each( subString, function( key, value ) {
var map1 = new Map();
div+='<p>'+JSON.stringify(key)+'</p>';
$.each( value, function( ky, val ) {
console.log('ky => '+ky);
console.log('val => '+val);
map1.set(ky, val);
div += '<p>'+JSON.stringify(ky)+'->'+JSON.stringify(val)+'</p>';
div += '<br/><br/>'
});
map2.set(key, map1);
});
} catch(e) {
alert(e);
}
}
div += '</div>';
$('body').append(div);
$('#mobiusSSOverlayDialog').dialog({
autoOpen: false,
modal: false,
title: 'Unique URLs on Page (press "Esc" button to close)',
position: {
at: 'right top'
},
width: windowWidth,
height: windowHeight,
zIndex: 11111111,
buttons: [
{
text: 'Close',
click: function () {
$(this).dialog('close');
}
}
]
});
//}
$("#SSButton").click(function() {
($("#SSOverlayDialog").dialog("isOpen") == false) ? $("#SSOverlayDialog").dialog("open") : $("#SSOverlayDialog").dialog("close") ;
});
var jqUI_CssSrc = GM_getResourceText('jqUI_CSS');
jqUI_CssSrc = jqUI_CssSrc.replace(/\.ui-front \{[\s]*z-index:\s100\;[\s]*\}/g,".ui-front \{\n z-index: 10000000 \; \n\}");
GM_addStyle(jqUI_CssSrc);
//--- Style our newly added elements using CSS.
GM_addStyle ( multilineStr ( function () {/*!
#SSButton {
background-repeat: no-repeat;
position: absolute;
top: 50%;
right: 0;
z-index: 22222222;
width: 40px;
height: 40px;
}
*/} ) );
function multilineStr (dummyFunc) {
var str = dummyFunc.toString ();
str = str.replace (/^[^\/]+\/\*!?/, '') // Strip function () { /*!
.replace (/\s*\*\/\s*\}\s*$/, '') // Strip */ }
.replace (/\/\/.+$/gm, '') // Double-slash comments wreck CSS. Strip them.
;
return str;
}
$.Coral = function (options) {
$.extend(options, {
data: JSON.stringify(options.data),
dataType: 'json',
type: 'POST',
async: false,
contentType: 'application/json',
processData: false,
headers: {
'Content-Encoding': 'abc',
'Target': options.operation
},
dataFilter: function(data, type) {
return data || "{}";
}
});
return $.ajax(options);
};
$.MyService = function (options) {
$.extend(options, {
url: "link to myservice",
operation: 'dummyOperation'
});
return $.Coral(options);
};
我在警告框中收到以下错误消息:
TypeError: $.MyService is not a function
有人可以帮助解决这个问题吗?
我在 Whosebug 本身上查找了问题,但找不到与此相关的先前问题。
你在最后定义它之前调用 $.MyService()
。声明为
的函数
var functionName = function () {...
仅在范围内为它之后的代码定义,而声明为
的函数
function functionName() {...
为同一范围内的所有代码定义。
我有 JavaScript 运行 对服务器进行 ajax 调用。
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script type="text/javascript">
var div = '<div id="OverlayDialog">';
$.Coral = function (options) {
$.extend(options, {
data: JSON.stringify(options.data),
dataType: 'json',
type: 'POST',
async: false,
contentType: 'application/json',
processData: false,
headers: {
'Content-Encoding': 'abc',
'Target': options.operation
},
dataFilter: function(data, type) {
return data || "{}";
}
});
return $.ajax(options);
};
$.MyService = function (options) {
$.extend(options, {
url: "link to myservice",
operation: 'dummyOperation'
});
return $.Coral(options);
};
function test() {
try {
var myOptionsData = {
storeUrlList: [document.getElementById('normalizedStoreUrl1').value,document.getElementById('normalizedStoreUrl2').value]
};
var myOptions = {data: myOptionsData,crossDomain: true};
response = $.MyService(myOptions).responseText;
var subString = "";
var startIndex = response.indexOf('{',1);
var endIndex = response.lastIndexOf('}');
responseText = response.substring(startIndex,endIndex);
var subString = JSON.parse(responseText);
var map2 = new Map();
$.each( subString, function( key, value ) {
var map1 = new Map();
div+='<p>'+JSON.stringify(key)+'</p>';
$.each( value, function( ky, val ) {
console.log('ky => '+ky);
console.log('val => '+val);
map1.set(ky, val);
div += '<p>'+JSON.stringify(ky)+':'+JSON.stringify(val)+'</p>';
});
});
} catch(e) {
alert(e);
}
div += '</div>';
$('body').append(div);
return false;
}
</script>
脚本对我来说运行得很好。 我想将其转换为 greasemonkey 脚本,同时使用 jqueryUI 对话框在单独的对话框中显示结果。创建覆盖对话框并将数据写入其中的部分工作正常,但我无法在用户脚本中执行 .$MyOptions 和 .$Coral 函数。
下面是我使用的用户脚本:
// ==UserScript==
// @name Get Data for each unique URL
// @namespace SellerSupportScript
// @include *
// @require http://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js
// @require http://ajax.googleapis.com/ajax/libs/jquery/ui/1.11.0/jquery-ui.min.js
// @resource jqUI_CSS http://ajax.googleapis.com/ajax/libs/jqueryui/1.11.3/themes/redmond/jquery-ui.css
// @grant GM_addStyle
// @grant GM_getResourceText
// @grant GM_getResourceURL
// @run-at document-end
// allow pasting
// ==/UserScript==
var snapshotResults = document.evaluate('//a[contains(@href,"http")]/@href', document, null, XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE, null);
var windowWidth = $(window).width()-800;
var windowHeight = 'auto';
var div = '<div id="SSOverlayDialog">';
var zNode = document.createElement ('input');
zNode.setAttribute ('id', 'SSButton');
zNode.setAttribute( 'type', 'image' );
zNode.setAttribute( 'src', 'http://www.veryicon.com/icon/64/System/Longhorn%20R2/Back%20Button.png');
document.body.appendChild (zNode);
var uniqueHostnameSet = new Set();
var uniqueURLArray = [];
uniqueHostnameSet.add(window.location.hostname);
var finalUrl = window.location.protocol + '//' + window.location.hostname;
uniqueURLArray.push(finalUrl);
var linkToDisplay = '<a href="' + finalUrl + '">' + finalUrl + '</a>';
linkToDisplay += '<br/><br/>';
div += linkToDisplay;
for (var iterate = 0; iterate < snapshotResults.snapshotLength; iterate++)
{
var hrefContent = snapshotResults.snapshotItem(iterate).textContent;
var regex = /http.*/;
var href = regex.exec(hrefContent);
var a = document.createElement('a');
a.href = href;
if (!uniqueHostnameSet.has(a.hostname))
{
uniqueHostnameSet.add(a.hostname);
finalUrl = a.protocol + '//' + a.hostname;
uniqueURLArray.push(finalUrl);
linkToDisplay = '<a href="' + finalUrl + '">' + finalUrl + '</a>';
linkToDisplay += '<br/><br/>';
div += linkToDisplay;
}
}
var size = 10;
for (var i=0; i<uniqueURLArray.length; i+=size) {
var urlList = uniqueURLArray.slice(i,i+size);
try {
var myOptionsData = {
storeUrlList: urlList
};
var myOptions = {data: myOptionsData,crossDomain: true};
response = $.MyService(myOptions).responseText;
var subString = "";
var startIndex = response.indexOf('{',1);
var endIndex = response.lastIndexOf('}');
responseText = response.substring(startIndex,endIndex);
var subString = JSON.parse(responseText);
var AttributeMap = {};
var map2 = new Map();
$.each( subString, function( key, value ) {
var map1 = new Map();
div+='<p>'+JSON.stringify(key)+'</p>';
$.each( value, function( ky, val ) {
console.log('ky => '+ky);
console.log('val => '+val);
map1.set(ky, val);
div += '<p>'+JSON.stringify(ky)+'->'+JSON.stringify(val)+'</p>';
div += '<br/><br/>'
});
map2.set(key, map1);
});
} catch(e) {
alert(e);
}
}
div += '</div>';
$('body').append(div);
$('#mobiusSSOverlayDialog').dialog({
autoOpen: false,
modal: false,
title: 'Unique URLs on Page (press "Esc" button to close)',
position: {
at: 'right top'
},
width: windowWidth,
height: windowHeight,
zIndex: 11111111,
buttons: [
{
text: 'Close',
click: function () {
$(this).dialog('close');
}
}
]
});
//}
$("#SSButton").click(function() {
($("#SSOverlayDialog").dialog("isOpen") == false) ? $("#SSOverlayDialog").dialog("open") : $("#SSOverlayDialog").dialog("close") ;
});
var jqUI_CssSrc = GM_getResourceText('jqUI_CSS');
jqUI_CssSrc = jqUI_CssSrc.replace(/\.ui-front \{[\s]*z-index:\s100\;[\s]*\}/g,".ui-front \{\n z-index: 10000000 \; \n\}");
GM_addStyle(jqUI_CssSrc);
//--- Style our newly added elements using CSS.
GM_addStyle ( multilineStr ( function () {/*!
#SSButton {
background-repeat: no-repeat;
position: absolute;
top: 50%;
right: 0;
z-index: 22222222;
width: 40px;
height: 40px;
}
*/} ) );
function multilineStr (dummyFunc) {
var str = dummyFunc.toString ();
str = str.replace (/^[^\/]+\/\*!?/, '') // Strip function () { /*!
.replace (/\s*\*\/\s*\}\s*$/, '') // Strip */ }
.replace (/\/\/.+$/gm, '') // Double-slash comments wreck CSS. Strip them.
;
return str;
}
$.Coral = function (options) {
$.extend(options, {
data: JSON.stringify(options.data),
dataType: 'json',
type: 'POST',
async: false,
contentType: 'application/json',
processData: false,
headers: {
'Content-Encoding': 'abc',
'Target': options.operation
},
dataFilter: function(data, type) {
return data || "{}";
}
});
return $.ajax(options);
};
$.MyService = function (options) {
$.extend(options, {
url: "link to myservice",
operation: 'dummyOperation'
});
return $.Coral(options);
};
我在警告框中收到以下错误消息:
TypeError: $.MyService is not a function
有人可以帮助解决这个问题吗?
我在 Whosebug 本身上查找了问题,但找不到与此相关的先前问题。
你在最后定义它之前调用 $.MyService()
。声明为
var functionName = function () {...
仅在范围内为它之后的代码定义,而声明为
的函数function functionName() {...
为同一范围内的所有代码定义。