2017-04-09 132 views
1

该脚本旨在被注入维基百科网站。它将使用用户的登录凭证发布到编辑API。如何使用Wikipedia API在浏览器上编辑页面javascript?

这是我的尝试:

function getEditToken(){ 
    return fetch(
     'https://en.wikipedia.org/w/api.php?action=query&meta=tokens&format=json', 
     {credentials: 'include'} 
    ) 
    .then(r => r.json()) 
    .then(r => r.query.tokens.csrftoken) 
} 

function writeRevision(title, text, summary){ 
    var url = `https://en.wikipedia.org/w/index.php?action=edit` 
    var formData = new FormData() 
    formData.append('title', title) 
    formData.append('text', text) 
    formData.append('summary', summary)  
    formData.append('contentmodel', 'wikitext') 

    var option = { 
     method: 'POST', 
     body: formData, 
     credentials: 'include', 
    } 

    return getEditToken() 
    .then(token => { formData.append('token', token); console.log(token) }) 
    .then(x => fetch(url, option)) 
    .then(r => r.text()) 
    .then(console.log) 
    .catch(e => console.log(e)) 

} 

writeRevision('User:eeeeeeeee/draft_1', 'foo wikitext', 'foo summary') 

回应说:

编辑表单的某些部分没有到达服务器;请仔细检查 您的编辑是否完整,然后重试。

+0

您是否包含编辑维基百科页面时通常发送的隐藏字段?比较使用脚本和常规维基百科时,chrome日志到“网络”选项卡时是否发送相同的字段? –

回答

2

使用the MediaWiki edit API来编辑页面。请勿直接张贴至?action=edit;该URI用于交互式客户端。

MediaWiki的API文档,包括如何使用JavaScript,我已经录如下做到这一点的例子:如果代码在浏览器中运行

function addNewSection(summary, content, editToken) { 
    $.ajax({ 
     url: mw.util.wikiScript('api'), 
     data: { 
      format: 'json', 
      action: 'edit', 
      title: mw.config.get('wgPageName'), 
      section: 'new', 
      summary: summary, 
      text: content, 
      token: editToken 
     }, 
     dataType: 'json', 
     type: 'POST', 
     success: function(data) { 
      if (data && data.edit && data.edit.result == 'Success') { 
       window.location.reload(); // reload page if edit was successful 
      } else if (data && data.error) { 
       alert('Error: API returned error code "' + data.error.code + '": ' + data.error.info); 
      } else { 
       alert('Error: Unknown result from API.'); 
      } 
     }, 
     error: function(xhr) { 
      alert('Error: Request failed.'); 
     } 
    }); 
} 
+0

非常感谢......又一天花在打字错误上。我挖掘源代码的行和行,并没有发现这一点。 – golopot

2

(因此能够访问到MediaWiki的JavaScript模块),您可以使用mw.Api.edit

function edit(title, text, summary) { 
    mw.loader.using('mediawiki.api.edit').then(function() { 
     let api = new mw.Api(); 
     api.edit(title, function() { 
      return { 
       text: text, 
       summary: summary 
      }; 
     }); 
    }); 
} 
相关问题