Make broken images handler ignore empty src images

closes CORE-1229

Test Plan:
  - Using Chrome
  - Create a course and set the syllabus as the home page.
  - Click on Home in the course navigation.
  - Click on another navigation items such as Assignments
  - Click the Back button in Chrome.
  - You go back appropriately, rather than getting a api json
    response

Change-Id: I6ed03896eed25514ddf35effe3f36e68344ade4d
Reviewed-on: https://gerrit.instructure.com/145844
Tested-by: Jenkins
Reviewed-by: Brent Burgoyne <bburgoyne@instructure.com>
Reviewed-by: Jeremy Stanley <jeremy@instructure.com>
QA-Review: Jeremy Putnam <jeremyp@instructure.com>
Product-Review: Clay Diffrient <cdiffrient@instructure.com>
This commit is contained in:
Clay Diffrient 2018-04-04 11:03:55 -06:00
parent 213cd4fac9
commit a5728ed7ae
2 changed files with 38 additions and 8 deletions

View File

@ -18,9 +18,10 @@
import $ from 'jquery'
import I18n from 'i18n!broken_images'
export default function attachErrorHandler(imgElement) {
export function attachErrorHandler(imgElement) {
$(imgElement).on('error', e => {
$.get(e.currentTarget.src)
if (e.currentTarget.src) {
$.get(e.currentTarget.src)
.fail(response => {
if (response.status === 403) {
// Replace the image with a lock image
@ -35,13 +36,19 @@ export default function attachErrorHandler(imgElement) {
$(e.currentTarget).addClass('broken-image')
}
})
} else {
// Add the broken-image class (if there is no source)
$(e.currentTarget).addClass('broken-image')
}
})
}
export function getImagesAndAttach () {
$('img[src!=""]')
.toArray()
.forEach(attachErrorHandler)
}
// this behavior will set up all broken images on the page with an error handler that
// can apply the broken-image class if there is an error loading the image.
$(document).ready(() =>
$('img')
.toArray()
.forEach(attachErrorHandler)
)
$(document).ready(() => getImagesAndAttach())

View File

@ -15,7 +15,7 @@
// You should have received a copy of the GNU Affero General Public License along
// with this program. If not, see <http://www.gnu.org/licenses/>.
import $ from 'jquery'
import attachErrorHandler from 'compiled/behaviors/broken-images'
import { attachErrorHandler, getImagesAndAttach } from 'compiled/behaviors/broken-images'
import {setTimeout} from 'timers'
let server
@ -69,3 +69,26 @@ test('on error handler sets appropriate alt text indicating the image is locked'
done()
}, 100)
})
QUnit.module('getImagesAndAttach', {
setup() {
$('#fixtures').html(
`<img id="borked" src="broken_image.jpg" alt="broken">
<img id="empty_src" src alt="empty_src">
`
)
},
teardown() {
$('#fixtures').empty()
}
});
test('does not attach error handler to images with an empty source', () => {
getImagesAndAttach()
ok(!$('img#empty_src').data('events'))
})
test('attaches error handler to elements with a non-empty source', () => {
getImagesAndAttach()
ok($('img#borked').data('events').error)
})