我正在编写一个书签,我希望它也能在浏览器控制台中工作。
为了更容易理解,代码向服务器进行异步 API 调用(模仿真实的;这是完全合法的)。它应该更改我单击编辑的消息,在消息开头添加“Text-1”,然后保存消息。
javascript:(async function(){
var msgIdInChange = '';
var targetNode = '';
var textOfMsgInChange = '';
var textToInsert = '';
msgIdInChange = document.getElementsByClassName('editing-message')[0].getAttribute('msg-id'); /*getting msg-id of the actively editing message*/
targetNode = document.querySelector("[node-id=" +CSS.escape(msgIdInChange)+ "]"); /*getting targetNode by msg-id from DOM*/
textOfMsgInChange = targetNode.innerText;
textToInsert = 'Text-1: ' + textOfMsgInChange;
var currentChatId = '';
var myToken = '';
currentChatId = document.getElementById('currentChat').getAttribute('mail');
myToken = JSON.parse(window.localStorage._connectData).aimsid; /*session token*/
var encodifyText = function(txt){
var temp = [];
var returnVal = '';
temp = txt.split('\n');
for (i=0; i<temp.length; i++){
returnVal += encodeURIComponent(txt.split('\n')[i]) + '%0A';
}
return returnVal.slice(0,-3); /*Delete last newline*/
};
var changeMessageFunc = async function(){
const response = await fetch('https://needed.site/api/sendIM', {
'headers': {
'accept': '*/*',
'content-type': 'application/x-www-form-urlencoded',
'sec-fetch-dest': 'empty',
'sec-fetch-mode': 'cors',
'sec-fetch-site': 'same-site'
},
'referrer': 'https://needed.site/',
'referrerPolicy': 'strict-origin-when-cross-origin',
'body': 't=' +encodeURIComponent(currentChatId)+ '&message=' +encodifyText(textToInsert)+ '&updateMsgId=' +msgIdInChange+ '&f=json&aimsid=' +encodeURIComponent(myToken),
'method': 'POST',
'mode': 'cors',
'credentials': 'omit'
});
};
await changeMessageFunc();
})();
问题在于 API 调用中消息的新行写法类似于
%0A
。但是这个 %0A
破坏了小书签,将其一些代码放到了第二行。
我该怎么办?
PS:谢谢!
%25A0
适用于我的书签。但是,该代码在浏览器控制台中失败。此外,有时代码会删除消息末尾的两个符号。是否可以让它在任何地方都有效?
只需将您的书签的
%
符号替换为 %25
。
returnVal += encodeURIComponent(txt.split('\n')[i]) + '%250A';
PS:由于您的小书签和浏览器控制台有不同的行为,因此这似乎会更好:
var encodifyText = function(txt){
var temp = [];
var returnVal = '';
temp = txt.split('\n');
for (i=0; i<temp.length; i++){
returnVal += encodeURIComponent(txt.split('\n')[i]) + decodeURI('%250A');
}
return returnVal.slice(0, returnVal.lastIndexOf(decodeURI('%250A'))); /*Delete last newline*/
};
由于
%25
不会破坏您的书签,因此 decodeURI('%250A')
可以像 %0A
一样正常工作。
我们最好使用
.slice(0,-3)
而不是 .slice(0, returnVal.lastIndexOf(decodeURI('%250A')))
,因为我们不确定换行符可能需要多少个符号。
我希望这有帮助。