inject-tools.js 3.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. import Settings from '../options/settings.js';
  2. export default (() => {
  3. /**
  4. * 如果tabId指定的tab还存在,就正常注入脚本
  5. * @param tabId 需要注入脚本的tabId
  6. * @param codeConfig 需要注入的代码
  7. * @param callback 注入代码后的callback
  8. */
  9. let injectScriptIfTabExists = function (tabId, codeConfig, callback) {
  10. chrome.tabs.query({currentWindow: true}, (tabs) => {
  11. tabs.some(tab => {
  12. if (tab.id !== tabId) return false;
  13. Settings.getOptions((opts) => {
  14. if (!codeConfig.hasOwnProperty('allFrames')) {
  15. codeConfig.allFrames = String(opts['CONTENT_SCRIPT_ALLOW_ALL_FRAMES']) === 'true';
  16. }
  17. codeConfig.js = 'try{' + codeConfig.js + ';}catch(e){};';
  18. // 有文件就注入文件
  19. if(codeConfig.files && codeConfig.files.length){
  20. // 注入样式
  21. if(codeConfig.files.join(',').indexOf('.css') > -1) {
  22. chrome.scripting.insertCSS({
  23. target: {tabId, allFrames: codeConfig.allFrames},
  24. files: codeConfig.files
  25. }, function () {
  26. callback && callback.apply(this, arguments);
  27. });
  28. }
  29. // 注入js
  30. else {
  31. chrome.scripting.executeScript({
  32. target: {tabId, allFrames: codeConfig.allFrames},
  33. files: codeConfig.files
  34. }, function () {
  35. chrome.scripting.executeScript({
  36. target: {tabId, allFrames: codeConfig.allFrames},
  37. func: function(code){try{evalCore.getEvalInstance(window)(code)}catch(x){}},
  38. args: [codeConfig.js]
  39. }, function () {
  40. callback && callback.apply(this, arguments);
  41. });
  42. });
  43. }
  44. }else if(codeConfig.css){
  45. // 注入css样式
  46. chrome.scripting.executeScript({
  47. target: {tabId, allFrames: codeConfig.allFrames},
  48. css:codeConfig.css
  49. }, function () {
  50. callback && callback.apply(this, arguments);
  51. });
  52. }else{
  53. // 注入js脚本
  54. chrome.scripting.executeScript({
  55. target: {tabId, allFrames: codeConfig.allFrames},
  56. func: function(code){try{evalCore.getEvalInstance(window)(code)}catch(x){}},
  57. args: [codeConfig.js]
  58. }, function () {
  59. callback && callback.apply(this, arguments);
  60. });
  61. }
  62. });
  63. return true;
  64. });
  65. });
  66. };
  67. return { inject: injectScriptIfTabExists };
  68. })();